Versions Compared

Key

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

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, assertis 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
bgColor#ffcccc

void process(int index) {
  assert(index++ > 0 names.remove(null); /* side effect */
  /* ... */
}

...

Avoid the possibility of side effects in assertions.

Code Block
bgColor#ccccff

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

Risk Assessment

...