This rule raises an issue when a class defined within another class declares a field with the same name as a field in its enclosing outer class.
When a nested scope declares a variable with the same name as a variable in its containing scope, the nested variable shadows or hides the containing scope’s variable. This creates ambiguity about which variable is being referenced in the nested scope’s code.
In languages with nested scopes that allow access to containing scope members, when a variable name is reused, the nested scope’s variable takes precedence within that nested scope. To access the containing scope’s variable, you must use qualified syntax that explicitly references the outer scope, which is often overlooked.
This shadowing pattern creates several problems:
Variable shadowing is particularly problematic in larger nested structures where the relationship between nested and containing scope variables is not immediately visible. It violates the principle of least surprise and makes the code more error-prone.
In Java inner classes, when a field has the same name as a field in the outer class, the inner class field shadows the outer class field. To access
the outer class field from within the inner class, you must use the qualified syntax OuterClassName.this.fieldName, which is easy to
overlook and makes the code harder to understand.
The main impact is on code maintainability and reliability:
While this issue doesn’t typically cause runtime exceptions, it can lead to incorrect program behavior that manifests as data corruption or unexpected results.
The recommended fix is to rename the inner class field to have a distinct name. This eliminates ambiguity and makes the code’s intent clear.
class Outer {
private int count = 0;
class Inner {
private int count = 0; // Noncompliant
void increment() {
count++; // Which count is being incremented?
}
}
}
class Outer {
private int count = 0;
class Inner {
private int innerCount = 0;
void increment() {
innerCount++; // Clear which field is being modified
}
}
}