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.
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"); } } |
This compliant solution declares the class Vector
with a different name:
class MyVector { //other code } |
As a tenet, do not:
This noncompliant specimen reuses the name of the val instance field in the scope of an instance method.
class Vector { private int val = 1; private void doLogic() { int val; //... } } |
This solution ameliorates the issue by using a different name for the variable defined in the method scope.
private void doLogic() { int newValue; //... } |
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 |
TODO
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
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.
\[[Bloch 08|AA. Java References#Bloch 08]\] Puzzle 67: All Strung Out \[[FindBugs 08|AA. Java References#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)