...
This noncompliant code example demonstrates an action being carried out in an assertion. The idea is to delete all the null
names from the list; however, the boolean
expression is unexpectedly not evaluated when assertions are disabled.
Code Block | ||
---|---|---|
| ||
private ArrayList<String> names; 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 | ||
---|---|---|
| ||
private ArrayList<String> names; void process(int index) { boolean nullsRemoved = names.remove(null); assert nullsRemoved; // no side-effect // ... } |
Risk Assessment
Side effects in assertions results in program behavior that depends on whether assertions are enabled or disabled.
...