Private Method Could Be Static
ID |
java.method_could_be_static |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Efficiency |
Language |
Java |
Tags |
best-practice, efficiency |
Description
Reports private instance methods that do not access any instance state and could be declared static.
Rationale
A method that never reads or writes instance fields, never calls instance methods, and never uses this or super carries no dependency on the object’s state. Declaring such a method static communicates this independence clearly, avoids passing an unnecessary receiver, and enables minor JVM optimizations.
The rule is conservative: only private methods are flagged to avoid breaking API contracts for non-private methods. Methods annotated @Override, serialization hooks (readObject, writeObject, readResolve, writeReplace), and methods in non-static inner classes are excluded.
java.lang.Object’s methods — `toString, hashCode, equals, getClass, clone, finalize, wait, notify, notifyAll — are inherited by every class, so an unqualified call to one of them keeps the method instance-bound even when the class declares no superclass.
Members inherited from a superclass count as instance state too: an unqualified call to an inherited method, or an unqualified read of an inherited field, carries no this or super prefix, yet adding static would not compile. The superclass chain is resolved across files through the software model. When the superclass is not part of the analyzed code — a framework or library base class — its members cannot be listed, so no method of that class is reported at all; the rule degrades to a false negative rather than to an uncompilable suggestion.
// Bad -- method does not use instance state
public class Formatter {
private String format(int value) {
return "value=" + value;
}
}
Remediation
Add the static modifier to the method. Callers inside the same class do not need to change.
// Good -- declared static
public class Formatter {
private static String format(int value) {
return "value=" + value;
}
}