Reuse of names leads to obscuration or shadowing; that is, the names in the current scope mask those defined elsewhere. Name reuse creates ambiguity and burdens code maintenance, especially when code requires access to both the original named entity and the entity with the reused name. The problem is aggravated when the reused name is required to be defined in a different package.
According to the Java Language Specification [[JLS 2005]], Section 6.3.2, "Obscured Declarations"
A simple name may occur in contexts where it may potentially be interpreted as the name of a variable, a type, or a package. In these situations, the rules of §6.5 specify that a variable will be chosen in preference to a type, and that a type will be chosen in preference to a package.
This implies that a variable can obscure a type or a package, and a type can obscure a package name. Shadowing, on the other hand, refers to masking variables, fields, types, method parameters, labels, and exception handler parameters in a subscope. Both these differ from hiding wherein an accessible member (typically non-private) that should have been inherited by a subclass is forgone in lieu of a locally declared subclass member that assumes the same name.
In general, do not
- Reuse the name of a superclass
- Reuse the name of an interface
- Reuse the name of a field defined in a superclass
- Reuse the name of a field that appears in a different scope within the same method
- Reuse the name of a field, type, or another parameter across packages
Noncompliant Code Example
This noncompliant code example implements a class that reuses the name of the class java.util.Vector
. It attempts to introduce a different condition for the isEmpty()
method for interfacing with native legacy code, by overriding the corresponding method in java.util.Vector
.
A future programmer might not know about this extension and incorrectly use the custom Vector
class when his intention was to use the original java.util.Vector
class. The custom type Vector
can obscure a class name from another package (for example, java.util.Vector
), as specified by JLS 6.3.2 (see above). Should this occur, it can cause undesirable effects by violating the programmer's assumptions.
Well-defined import statements resolve these issues. However, when the definitions of the reused name are imported from other packages, use of the type-import-on-demand declaration (see Java Language Specification [[JLS 2005]], Section 7.5.2, "Type-Import-on-Demand Declaration") can lead to unexpected import of a class that was not intended. Moreover, a commonâ”and potentially misleadingâ”tendency is to produce the import statements after writing the code, often via automatic inclusion of import statements by an IDE. This creates further ambiguity with respect to the names; when a custom type is found earlier in the Java include path than the intended type, no further searches are conducted.
class Vector { private int val = 1; public boolean isEmpty() { if(val == 1) { //compares with 1 instead of 0 return true; } else { return false; } } //other functionality is same as java.util.Vector } // import java.util.Vector; omitted public class VectorUser { public static void main(String[] args) { Vector v = new Vector(); if(v.isEmpty()) { System.out.println("Vector is empty"); } } }
Compliant Solution
This compliant solution declares the class Vector
with a different name.
class MyVector { //other code }
Note: When the developer and organization control the original hidden class, in addition to the code being written, it may be preferable to change the design strategy of the original in accordance with Bloch's Effective Java [[Bloch 2008]] "Item 16: Prefer interfaces to abstract classes." Changing the original class into an interface would permit class MyVector
to declare that it implements the hypothetical Vector
interface. This would permit client code that intended to use MyVector
to remain compatible with code that uses the original implementation of Vector
.
Noncompliant Code Example
This noncompliant code example reuses the name of the val instance field in the scope of an instance method. This behavior can be classified as shadowing.
class Vector { private int val = 1; private void doLogic() { int val; //... } }
Compliant Solution
This solution eliminates shadowing by changing the name of the variable defined in method scope.
private void doLogic() { int newValue; //... }
Noncompliant Code Example
Method shadowing in different scopes becomes possible when two or more packages are used. Method shadowing differs from method overloading in that subclasses are allowed to inherit overloadings defined in the base class. It differs from hiding because the methods do not need to be declared static
. It is also distinct from method overriding, as exemplified in this noncompliant code example.
package x; public class A { void doLogic() { // default accessibility // print 'A' } public static void main(String[] args) { A a = new y.C(); a.doLogic(); // invokes doLogic() of class x.B and prints 'B' } } package x; public class B extends A { void doLogic() { // default accessibility // print 'B' } } package y; // different package public class C extends x.B { // public accessibility public void doLogic() { // print 'C' } }
Note that class y.C
is accessible from the package x
and so is its doLogic()
method. However, if the main()
method, defined in class A
, tries to polymorphically invoke y.doLogic()
as shown, the override corresponding to class B in package x
takes precedence. This is because the doLogic()
methods in classes x.A
and x.B
are not visible from class y.C
due to the default
access specifier. As a result, the class x.C
is not considered a part of the overriding hierarchy. Note, however, that the code behaves as expected if the access specifiers of all of the methods are changed to public
.
Compliant Solution
Use a different name to indicate that the class residing in another package is not intended to be part of the overriding chain. A programmer can use dotted notation to explicitly specify which class defines the method to be invoked. Avoid reusing names even when all the relevant classes define the affected methods with a public
access specifier; future evolution of one or more of the classes can reduce method accessibility, leading to unexpected results.
package x; public class A { void doLogic() { // print 'A' } public static void main(String[] args) { // explicitly invokes doSequence() of class y.C and prints 'C' y.C.doSequence(); } } package x; public class B { /* ... */ } package y; // different package public class C extends x.B { public void doSequence() { // now renamed // print 'C' } }
Exceptions
SCP02-EX1: Reuse of names is permitted for trivial loop counter declarations in the same scope:
for(int i = 0; i < 10; i++) { } for(int i = 0; i < 20; i++) { }
Risk Assessment
Name reuse makes code more difficult to read and maintain. This can result in security weaknesses.
Guideline |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
SCP02-J |
low |
unlikely |
medium |
P2 |
L3 |
Automated Detection
An automated tool can easily detect reuse of names whose earlier definition appears somewhere in the Java include path. FindBugs, for example, detects at least four sub-instances of this guideline.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
Related Guidelines
C Secure Coding Standard: DCL01-C. Do not reuse variable names in subscopes
C++ Secure Coding Standard: DCL01-CPP. Do not reuse variable names in subscopes
Bibliography
[[JLS 2005]] Section 6.3.2 "Obscured Declarations", Section 6.3.1 "Shadowing Declarations", Section 14.4.3 "Shadowing of Names by Local Variables"
[[Bloch 2005]] Puzzle 67: All Strung Out
[[Bloch 2008]] Item 16: Prefer interfaces to abstract classes
[[Kabanov 2009]]
[[Conventions 2009]] 6.3 Placement
[[FindBugs 2008]]:
Nm: Class names shouldn't shadow simple name of implemented interface
Nm: Class names shouldn't shadow simple name of superclass
MF: Class defines field that masks a superclass field
MF: Method defines a variable that obscures a field
SCP01-J. Do not increase the accessibility of overridden or hidden methods 05. Scope (SCP) SCP03-J. Do not expose sensitive private members of the outer class from within a nested class