The assert
statement is a convenient mechanism for incorporating diagnostic tests in code. Expressions used with the standard assert
statement must avoid side effects. Typically, the behavior of the assert
statement depends on the status of a runtime property. When enabled, the assert
statement is designed to evaluate its expression argument and throw an AssertionError
if the result of the expression is false
. When disabled, assert
is defined to be a no-op; any side effects resulting from evaluation of the expression in the assertion are lost when assertions are disabled. Consequently, programs must not use side-effecting expressions in assertions.
Noncompliant Code Example
This noncompliant code is attempting to delete all the null
names from the list in an assertion. However, the boolean
expression is not evaluated when assertions are disabled.
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.
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.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
EXP06-J |
low |
unlikely |
low |
P3 |
L3 |
Automated Detection
Automated detection of assertion operands that contain locally visible side effects is straightforward. Some analyses could require programmer assistance to determine which method invocations lack side effects.
Related Guidelines
Bibliography
EXP05-J. Do not write more than once to the same variable within an expression 02. Expressions (EXP) 03. Numeric Types and Operations (NUM)