Assertions in Java: which single guideline is correct and reflects best practice?
-
AAssertion expressions should not contain side effects.
-
BAssertion expression values can be any primitive type.
-
CAssertions should be used for enforcing preconditions on public methods.
-
DAn AssertionError thrown as a result of a failed assertion should always be handled by the enclosing method.
-
ENone of the above
Answer
Correct Answer: Assertion expressions should not contain side effects.
Explanation
Introduction / Context:The assert statement is a tool for verifying developer assumptions. Because assertions can be disabled at runtime, code inside assertion expressions should not alter program state in ways the application depends on.
Given Data / Assumptions:
- Assertions may be disabled with JVM flags, causing both the condition and the optional detail expression to be skipped.
- Public API argument validation should be implemented with explicit checks and exceptions, not assertions.
- AssertionError indicates a bug, not a recoverable condition.
Concept / Approach:Assess each option against widely accepted guidelines: no side effects, not for public preconditions, and no requirement to “handle” AssertionError.
Step-by-Step Solution:A: True. If an assertion has side effects, disabling assertions removes those effects, changing program behavior—an anti-pattern. Keep assertions free of side effects.B: False. The main boolean expression must be boolean; the detail expression after the colon can be any expression, but that is not what “assertion expression values can be any primitive type” suggests.C: False. Public preconditions should not rely on assertions because they may be disabled; use exceptions (e.g., IllegalArgumentException).D: False. You normally do not catch AssertionError; it signals a programming error.
Verification / Alternative check:Disable assertions with -da and confirm that any side effects placed inside assertions do not occur; this demonstrates why they are dangerous.
Why Other Options Are Wrong:They either misstate typing rules or recommend misuses for public contracts and exception handling.
Common Pitfalls:Putting logging, counters, or state changes inside assertions; validating user input with assert; catching AssertionError to continue.
Final Answer:Assertion expressions should not contain side effects.