Reuse of names leads to shadowing, that is, the names in the current scope mask those defined elsewhere. This creates ambiguity especially when the originals need to be used and also leaves the code hard to maintain. The problem gets aggravated when the reused name is defined in a different package.
Noncompliant Code Example
This noncompliant example implements a class that reuses the name of class java.util.Vector
. The intent of this class is to introduce a different condition for the isEmpty
method for native legacy code interfacing. A future programmer may not know about this extension and may incorrectly use the Vector
idiom to use the original Vector
class. This behavior is clearly undesirable.
Well defined import statements do resolve these issues but may get confusing when the reused name is defined in a different package. Moreover, a common (and misleading) tendency is to include the import statements after writing the code (many IDEs allow automatic inclusion as per requirements). As a result, such instances can go undetected.
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; public class VectorUser { public static void main(String[] args) { Vector v = new Vector(); if(v.isEmpty()) System.out.println("Vector is empty"); } }
Compliant Solution
As a tenet, 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 the same method (in different scope)
This compliant solution declares the class Vector
with a different name:
class MyVector { //other code }
Risk Assessment
Reusing names leads to code that is harder to read and maintain and may result in security weaknesses.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
SCP03-J |
low |
unlikely |
medium |
P2 |
L3 |
Automated Detection
TODO
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
Other Languages
This rule appears in the C Secure Coding Standard as DCL01-C. Do not reuse variable names in subscopes.
This rule appears in the C++ Secure Coding Standard as DCL01-CPP. Do not reuse variable names in subscopes.
References
[[Bloch 08]] Puzzle 67: All Strung Out
[[FindBugs 08]]:
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
SCP02-J. Use nested classes carefully 03. Scope (SCP) 04. Integers (INT)