JavaScript is not currently enabled, but is required for full CodeSonar manual search and browse functionality.

If you are viewing this file in your hub's Web GUI, enable JavaScript in your browser: you will also need it for GUI functionality.

If you opened this file directly from disk, your browser may be directly suppressing JavaScript functionality: certain browsers perform this suppression on local files (but not files delivered by web servers) for security reasons.

CodeSonar® 9.2p0 CONFIDENTIAL CodeSecure Inc
Java


JAVA.STRUCT.UNFLD : Unnecessary Field (Java)

Summary

One of the following.

Properties

Class Name Unnecessary Field (Java)
Significance reliability
Mnemonic JAVA.STRUCT.UNFLD
Categories
CWE CWE:563 Assignment to Variable without Use
  CWE:1126 Declaration of Variable with Unnecessarily Wide Scope
Availability Available for Java and Kotlin.
Enabling Checks for this warning class are enabled by default. To disable them, add the following WARNING_FILTER rule to the project configuration file.
WARNING_FILTER += discard class="Unnecessary Field (Java)"

Example

// 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;
  }
}

Resolution

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

Relevant Configuration File Parameters

The following configuration file parameters affect checks for this warning class.

 

To report problems with this documentation, please visit https://support.codesecure.com/.