The assert()
method statement is a convenient mechanism for incorporating diagnostic tests in code. Expressions used with the standard assert
method statement should not have side effects. Typically, the behavior of the assert
method statement depends on the status of a runtime property. If defined, the assert
method statement is defined to evaluate its expression argument and abort if the result of the expression is convertible to false
. If undefined, assert
is defined to be a no-op. Consequently, any side effects resulting from evaluation of the expression in the assertion are lost in non-debugging versions of the code.
Noncompliant Code Example
Code Block | ||
---|---|---|
| ||
void process(int index) { assert(index++ > 0 names.remove(null); /* side effect */ /* ... */ } |
...
Avoid the possibility of side effects in assertions.
Code Block | ||
---|---|---|
| ||
void process(int index) { boolean nullsRemoved = assert(index > 0)names.remove(null); assert nullsRemoved; /* no side effect */ ++index; /* ... */ } |
Risk Assessment
...