Java


JAVA.STRUCT.SE.ASSERT : Assertion Contains Side Effects (Java)

要旨

An assertion checks a condition with side-effects.

If an assertion has side effects, the semantics of the program will change depending on whether or not assertions are enabled.

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.

プロパティ

クラス名 Assertion Contains Side Effects (Java)
日本語クラス名 Assertion Contains Side Effects (Java)
クラス分類 信頼性 (reliability)
ニーモニック JAVA.STRUCT.SE.ASSERT
カテゴリー
CWE CWE:665 Improper Initialization
CERT-Java CERT-Java:DCL00-J Prevent class initialization cycles
  CERT-Java:EXP06-J Expressions used in assertions must not produce side effects
対応言語 Java で利用可能です。
有効/無効設定 このワーニングクラスのチェックはデフォルトで有効になっています。チェックを無効にするにはプロジェクト設定ファイル (configuration file)に以下の WARNING_FILTER ルールを追加してください。
WARNING_FILTER += discard class="Assertion Contains Side Effects (Java)"

The assert statements in the following code fragment check expressions whose evaluations have side effects: each checked expression updates a variable or field.

public class AssertionsWithSideEffects {
  public void assert1() {
      Object obj = null;
      assert (obj = new Object()) != null;       // "Assertion Contains Side Effects (Java)" warning issued here
  }

  public void assert2() {
      assert (list = new ArrayList<>()) != null; // "Assertion Contains Side Effects (Java)" warning issued here
  }

  public void assert3() {
      assert counter++ > 17;                     // "Assertion Contains Side Effects (Java)" warning issued here
  }

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

There are generally two options for resolving a situation where an assertion contains a side effect: either remove the side effect entirely, or move it outside the assert statement. For example, method assert1() could be rewritten as follows.

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

解決法

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.

関連のある設定ファイルパラメータ

設定ファイルの以下のパラメータがこのワーニングクラスのチェックに影響します。