Unused Private Field
ID |
java.unused_private_field |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Code Smell |
Language |
Java |
Tags |
CWE:563, code-style, unused-code |
Description
Reports private fields that are never referenced anywhere in the class body.
A field a framework populates by reflection is not reported: Mockito’s @Mock/@Spy/@Captor,
Spring Boot’s @MockBean/@MockitoBean bean overrides, JPA mapping (@Id, @GeneratedValue,
@Version, @Column) and JavaFX @FXML. @Autowired, @Inject and @Resource are deliberately
not exempt — an injected dependency nothing reads is dead weight worth removing.
Rationale
A private field that is never read or written (beyond its declaration) is dead code. It consumes memory at runtime, clutters the class, and may mislead readers into thinking it plays a role. It often results from incomplete refactoring or abandoned functionality.
// Bad -- field is never used
public class Account {
private int obsoleteCounter = 0;
private String name;
public String getName() { return name; }
}
// Good -- only keep fields that are referenced
public class Account {
private String name;
public String getName() { return name; }
}
Remediation
Remove the unused field. If it was intended for future use, add it when actually needed.