Unused private fields should be removed

Java pattern

Unused private fields constitute dead code and should therefore be removed.


Apply with the Grit CLI
grit apply unused_private_fields

Removes unused fields and preserves used fields

BEFORE
public class MyClass {
  private int foo = 42;
  private int bar = 24;
  public String baz = "papaya";

  public int compute(int a) {
    return a * bar + 42;
  }
}
AFTER
public class MyClass {
  private int bar = 24;
  public String baz = "papaya";

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

Does not remove serialization ID fields

JAVA
public class MyClass implements java.io.Serializable {
  private static final long serialVersionUID = 42L;
}

Does not remove annotated fields

JAVA
public class MyClass {
  @SomeAnnotation
  private int unused;
}

Does not remove fields with native modifier

JAVA
public class MyClass {
  private native static void doSomethingNative();
}

Does not remove fields used in other fields

BEFORE
public class Test {

    private static final String HELLO = "Hello, ";
    private static final String WORLD = "World";

    private static final String HELLO_WORLD = HELLO + WORLD;
    private static final String REMOVE_THIS = "Remove this";

    private final String GREETING = "Hello, ";
    private final String NAME = "John";

    private final String GREETING_NAME = GREETING + NAME;

    public static void main(String[] args) {
        System.out.println(HELLO_WORLD);
        System.out.println(GREETING_NAME);
    }
}
AFTER
public class Test {

    private static final String HELLO = "Hello, ";
    private static final String WORLD = "World";

    private static final String HELLO_WORLD = HELLO + WORLD;

    private final String GREETING = "Hello, ";
    private final String NAME = "John";

    private final String GREETING_NAME = GREETING + NAME;

    public static void main(String[] args) {
        System.out.println(HELLO_WORLD);
        System.out.println(GREETING_NAME);
    }
}