Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider Java v3.0 (sch jp)

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 non-compliant 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). ThusAs a result, such instances can go undetected.

Code Block
bgColor#FFcccc
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");
  }
}

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)

...

Code Block
bgColor#ccccff
class MyVector {
  //other code
}

Risk Assessment

TODO

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

SCP03-J

??

??

??

P??

L??

Automated Detection

TODO

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

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