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 non-compliant 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). Thus, 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
}
public class VectorUser {
public static void main(String[] args) {
Vector v = new Vector();
if(v.isEmpty())
System.out.println("Vector is empty");
}
}
|
As a tenet, do not:
This compliant solution declares the class Vector with a different name:
class MyVector {
//other code
}
|
Java Puzzlers, 67
FINDBUGS -
1. Class names shouldn't shadow simple name of implemented interface
2. Class names shouldn't shadow simple name of superclass
3. Class defines field that masks a superclass field
4. Method defines a variable that obscures a field