...
Noncompliant Code Example
This noncompliant code is attempting attempts to delete all the null names from the list in an assertion. However, the boolean
Boolean expression is not evaluated when assertions are disabled.
Code Block | ||
---|---|---|
| ||
private ArrayList<String> names; void process(int index) { assert names.remove(null); // sideSide effect // ... } |
Compliant Solution
Avoid the The possibility of side effects in assertions . This can be achieved avoided by decoupling the boolean
Boolean expression from the assertion.:
Code Block | ||
---|---|---|
| ||
private ArrayList<String> names; void process(int index) { boolean nullsRemoved = names.remove(null); assert nullsRemoved; // noNo side effect // ... } |
Risk Assessment
Side effects in assertions result 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
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
CodeSonar |
| JAVA.STRUCT.SE.ASSERT | Assertion Contains Side Effects (Java) | ||||||
PVS-Studio |
| V6055 | |||||||
SonarQube |
| S3346 | Expressions used in "assert" should not produce side effects |
Related Guidelines
Android Implementation Details
The assert
statement is supported on the Dalvik VM but is ignored under the default configuration. Assertions may be enabled by setting the system property "debug.assert
" via: adb shell setprop debug.assert 1
or by sending the command-line argument "--enable-assert
" to the Dalvik VM.
Bibliography
...
02. Expressions (EXP) 03. Numeric Types and Operations (NUM)