Java


JAVA.STRUCT.UNFLD : Unnecessary Field (Java)

要旨

One of the following.

プロパティ

クラス名 Unnecessary Field (Java)
日本語クラス名 Unnecessary Field (Java)
クラス分類 信頼性 (reliability)
ニーモニック JAVA.STRUCT.UNFLD
カテゴリー
CWE CWE:563 Assignment to Variable without Use
  CWE:1126 Declaration of Variable with Unnecessarily Wide Scope
対応言語 Java で利用可能です。
有効/無効設定 このワーニングクラスのチェックはデフォルトで有効になっています。チェックを無効にするにはプロジェクト設定ファイル (configuration file)に以下の WARNING_FILTER ルールを追加してください。
WARNING_FILTER += discard class="Unnecessary Field (Java)"

// ImproperField.java
public class ImproperField {
  private int[] array = new int[100];
  private int counter;
  private static int id;
  public String TAG = "MY_TAG" + id++; // "Unnecessary Field (Java)" warning issued here
  public String prefix = TAG + ": ";   // "Unnecessary Field (Java)" warning issued here

  public void init() {
    for (counter = 0; counter < array.length; counter++)
      array[counter] = counter;
  }

  public String getError(String message) {
    return prefix + message;
  }

  public void clear() {
    for (counter = 0; counter < array.length; counter++)
      array[counter] = 0;

    counter = 0;                       // "Unnecessary Field (Java)" warning issued here
  }
}

Field counter is assigned inside each method that uses it, so could be replaced by local variables. For the same reason, the assignment at the end of clear() is useless and should be removed. Moreover, field TAG should be final since it is only used by the constructor of ImproperField.

For example, the code could be rewritten as follows.

// ImproperField.java, after modification
public class ImproperField {
  private int[] array = new int[100];
  private static int id;
  public final String TAG = "MY_TAG" + id++;
  public String prefix = TAG + ": ";

  public void init() {
    for (int counter = 0; counter < array.length; counter++)
      array[counter] = counter;
  }

  public String getError(String message) {
    return prefix + message;
  }

  public void clear() {
    for (int counter = 0; counter < array.length; counter++)
      array[counter] = 0;
  }
}

解決法

Use variables local to the methods and the constructors instead of fields.

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

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