The assert()
statement is a convenient mechanism for incorporating diagnostic tests in code. Expressions used with the standard assert
statement should not have contain side effects. Typically, the behavior of the assert
statement depends on the status of a runtime property. If enabled, the assert
statement is designed to evaluate its expression argument and throw an AssertionError
if the result of the expression is convertible to false
. If disabled, assert
is defined to be a no-operation. Consequently, any side effects resulting from evaluation of the expression in the assertion are lost in production quality code.
...
Code Block | ||
---|---|---|
| ||
void process(int index) { assert names.remove(null); /*/ side effect */ /*/ ... */ } |
Compliant Solution
Avoid the possibility of side effects in assertions. This can be achieved by decoupling the boolean
expression from the assertion.
Code Block | ||
---|---|---|
| ||
void process(int index) { boolean nullsRemoved = names.remove(null); assert nullsRemoved; /*/ no side effect */ /*/ ... */ } |
Risk Assessment
Side effects in assertions can lead to unexpected and erroneous behavior.
...