Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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.

Code Block
bgColor#ffcccc


private ArrayList<String> names;

void process(int index) {
  assert names.remove(null); // side-effect 
  // ...
}

...

Avoid the possibility of side effects in assertions. This can be achieved by decoupling the boolean expression from the assertion.

Code Block
bgColor#ccccff


private ArrayList<String> names;

void process(int index) {
  boolean nullsRemoved = names.remove(null);
  assert nullsRemoved; // no side-effect 
  // ... 
}

...

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

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

 

EXP05-J. Do not write more than once to the same variable within an expression      02. Expressions (EXP)      03. Numeric Types and Operations (NUM)