Parameter Shadows Field
ID |
java.parameter_shadows_field |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Code Smell |
Language |
Java |
Tags |
code-style, naming |
Rationale
When a parameter name shadows a field, the unqualified name inside the method body refers to the parameter, not the field. This is a common source of initialization bugs: the developer writes name = name (a no-op on the field) instead of this.name = name.
By default, constructors and setters are excluded because this.field = field is the standard Java/Spring DI convention in those contexts.
"Setter" here means the body is the assignment, not that the method is called setX and returns void. A fluent setter, a builder method with no set prefix, and a nested-builder method with a qualified return type all store their parameter the same way and are all excluded:
public Repositories setTotal(int total) { // not flagged
this.total = total;
return this;
}
public Builder membership(String membership) { // not flagged
this.membership = membership;
return this;
}
A method that derives the value it stores is not a setter, and its shadowing parameter is still reported — this.count = count + 1 leaves the reader to work out which count is which.
// Flagged -- non-setter method parameter shadows field
private String label;
public void update(String label) {
process(label); // is this the parameter or was this.label intended?
}
Remediation
Use a different name for the parameter:
// Good -- clear distinction
private String name;
public void setName(String newName) {
this.name = newName;
}