All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.java.rules.java.S1068.html Maven / Gradle / Ivy

Why is this an issue?

If a private field is declared but not used locally, its limited visibility makes it dead code.

This is either a sign that some logic is missing or that the code should be cleaned.

Cleaning out dead code decreases the size of the maintained codebase, making it easier to understand and preventing bugs from being introduced.

public class MyClass {
  private int foo = 42; // Noncompliant: foo is unused and should be removed

  public int compute(int a) {
    return a * 42;
  }

}

Note that this rule does not take reflection into account, which means that issues will be raised on private fields that are only accessed using the reflection API.

Exceptions

The rule admits 3 exceptions:

  • Serialization ID fields

The Java serialization runtime associates with each serializable class a version number called serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible for serialization.

A serializable class can declare its own serialVersionUID explicitly by declaring a field named serialVersionUID that must be static, final, and of type long. By definition, those serialVersionUID fields should not be reported by this rule:

public class MyClass implements java.io.Serializable {
  private static final long serialVersionUID = 42L;  // Compliant by exception
}
  • Annotated fields

The unused field in this class will not be reported by the rule as it is annotated.

public class MyClass {
  @SomeAnnotation
  private int unused;  // Compliant by exception
}
  • Fields from classes with native methods

The unused field in this class will not be reported by the rule as it might be used by native code.

public class MyClass {
  private int unused = 42;  // Compliant by exception
  private native static void doSomethingNative();
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy