Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Changed to Applicability, updated some references to Java 7

Reuse of identifier names in subscopes leads to obscuration or shadowing. The identifiers in the current scope render those defined elsewhere inaccessible. Although the Java Language Specification clearly resolves any syntactic ambiguity arising from obscuring or shadowing, such ambiguity burdens code maintainers, especially when code requires access to both the original named entity and the inaccessible one. The problem is exacerbated when the reused name is defined in a different package.

According to §6.34.2, "Obscured Declarations,Obscuring" of the Java Language Specification [JLS 20052011],

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§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.

...

Code Block
bgColor#ccccff
class MyVector {
  private void doLogic() {
    for (int i = 0; i < 10; i++) {/* ... */}
    for (int i = 0; i < 20; i++) {/* ... */} 
  }
}

...

Applicability

Name reuse makes code more difficult to read and maintain, which can result in security weaknesses.

...

Guideline

...

Severity

...

Likelihood

...

Remediation Cost

...

Priority

...

Level

...

DCL51-JG

...

low

...

unlikely

...

medium

...

P2

...

Automated Detection

An automated tool can easily detect reuse of names in containing scopes.

...

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 20052011]

§6.34.2, "Obscured DeclarationsObscuring"

 

§6.34.1, "Shadowing Declarations"

 

§7.5.2, "Type-Import-on-On_Demand DeclarationDeclarations"

 

§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] 

 

...

DCL55-JG. Minimize the scope of variables      01. Declarations and Initialization (DCL)      DCL16-J. Do not reuse public identifiers from the Java Standard Library

...