Difficulty: Easy
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:
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.
Discussion & Comments