Checker SideEffects

belongs to group Basic
Identify unexpected or suspicious side-effects

Frameworks supported by this checker

  • java up to 11
  • android up to API level 28

Warnings generated by this checker

  • SideEffectInAssertionWarning: an assertion checks a condition with side-effects [ CWE665 ]

Options accepted by this checker

  • none

Annotations understood by this checker

  • none


Description

Side-effects are updates to heap memory, such as variable, field or array assignment operations. They are essential in object-oriented code. However, there are situations where side-effects are unexpected or suspicious and should be avoided.

This checker identifies unexpected or suspicious side-effects.

Action: Check if the side-effect is actually wrong and avoid it, for instance by moving the expression with side-effect into a separate, isolated statement.

Examples

Consider the following code:

public class AssertionsWithSideEffects {
  public void assert1() {
    Object obj = null;
    assert (obj = new Object()) != null;
  }

  public void assert2() {
    assert (list = new ArrayList<>()) != null;
  }

  public void assert3() {
    assert counter++ > 17;
  }

  public List list = new ArrayList<>();
  private static int counter;
}

This checker issues the following warnings:

AssertionsWithSideEffects.java:4: [SideEffects: SideEffectInAssertionWarning] The evaluation of this assertion might induce side-effects
AssertionsWithSideEffects.java:8: [SideEffects: SideEffectInAssertionWarning] The evaluation of this assertion might induce side-effects
AssertionsWithSideEffects.java:12: [SideEffects: SideEffectInAssertionWarning] The evaluation of this assertion might induce side-effects

since the three assert statements check expressions whose evaluation has side-effects. Namely, those expressions update a variable or a field. This is suspicious, since the semantics of the program changes when assertions are turned on or off. In general, assert statements should not have side-effects.

In this example, the programmer should either avoid the side-effect, or move the side-effect outside of the assert statements. For instance, method assert1() could be rewritten as follows:

public void assert1() {
  Object obj = new Object();
  assert obj != null;
}