Java


JAVA.STRUCT.UUFIELD : Unused Field (Java)

Summary

A field is never read and never written.

Fields constitute the state of an object, that is, they are meant to store information that survives across method calls. It is hence useless to store information in a field that is never read. Moreover, that behavior is actually harmful, since writing into a useless field hinders the garbage collector. It is also pointless to read data from a field that is never written, since the default value for the field will be found there. Note that there are situations when a field is written by reflection, which cannot be understood by analyzer, in general. This is often the case of fields auto-wired through dependency injection. The analyzer knows some specific patterns, typically marked through code annotations, but cannot foresee all possibilities.

Properties

Class Name Unused Field (Java)
Significance reliability
Mnemonic JAVA.STRUCT.UUFIELD
Categories
CWE CWE:1164 Irrelevant Code
Availability Available for Java only.
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="Unused Field (Java)"

Example

public class Fields {
  private int f1;                         // Field Never Written (Java) warning issued here
  private final Object f2 = new Object(); // Field Never Read (Java) warning issued here
  private float f3;                       // Unused Field (Java) warning issued here

  public Fields() {
      System.out.println(f1);
  }

  public static void main(String args[]) {
      new Fields();
  }
}

In this example, all three fields are useless and could be removed, reducing the memory footprint of the instances of the class and helping the garbage collector.

Resolution

Remove all fields that are never read or never written.

Relevant Configuration File Parameters

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