Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Parasoft Jtest 2022.2

Reuse of identifier names in subscopes leads to obscuration or shadowing, that is, the names . Reused identifiers in the current scope mask can render 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 further aggravated inaccessible. Although the Java Language Specification (JLS) [JLS 2013] clearly resolves any syntactic ambiguity arising from obscuring or shadowing, such ambiguity burdens code maintainers and auditors, 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.

Wiki MarkupAccording to the Java Language Specification \[[JLS 05|AA. Java References#JLS 05]\] section 6.3.2 Obscured Declarations:to §6.4.2, "Obscuring," of the JLS [JLS 2013],

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

As This implies that a result a variable can obscure a type or a package, and a type can obscure a package name. Shadowing, on the other hand refers to masking of variables, fields, types, method parameters, labels and exception handler parameters in a subscope. Both these differ from hiding wherein a member , refers to one variable rendering another variable inaccessible in a containing scope. One type can also shadow another type.

No identifier should obscure or shadow another identifier in a containing scope. For example, a local variable should not reuse the name of a class field or method or a class name or package name. Similarly, an inner class name should not reuse the name of an outer class or package.

Both overriding and shadowing differ from hiding, in which an accessible member (typically nonprivate) that should have been inherited by a subclass is forgone in lieu of replaced by a locally declared subclass member , that assumes the same name .

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 some different scope)
  • Reuse the name of a field, type or another parameter across packages

Wiki Markup
It is permissible to declare a label with the same name as another variable in the same scope. This is because there is no obscuration in this case \[[JLS 05|AA. Java References#JLS 05]\].

Noncompliant Code Example

This noncompliant example implements a class that reuses the name of the class java.util.Vector. It attempts to introduce a different condition for the isEmpty method for interfacing with native legacy code, by overriding the corresponding method in java.util.Vector.

A future programmer may not know about this extension and may incorrectly use the Vector idiom to use the original java.util.Vector class, by adding an import statement. Because a type (Vector class) can obscure a package name (java.util.Vector), the custom class Vector defined in the same package as VectorUser, takes precedence. This causes undesirable effects by violating the programmer's assumptions.

but has a different, incompatible method signature.

Noncompliant Code Example (Field Shadowing)

This noncompliant code example reuses the name of the val instance field in the scope of an instance methodWell 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). This can create even more ambiguity with respect to the names.

Code Block
bgColor#FFcccc

class VectorMyVector {
  private int val = 1;
  publicprivate booleanvoid isEmptydoLogic() {
    if(val == 1)   //compares with 1 instead of 0
      return trueint val;
    else
      return false;
  }
  //other functionality is same as java.util.Vector
}

import java.util.Vector; // desired functionality (line added later)

public class VectorUser {
  public static void main(String[] args) {
    Vector v = new Vector();
    if(v.isEmpty())
      System.out.println("Vector is empty");
  }
}

Compliant Solution

This compliant solution declares the class Vector with a different name.

Code Block
bgColor#ccccff

class MyVector {
  //other code
}

Noncompliant Code Example

This noncompliant code specimen reuses the name of the val instance field in the scope of an instance method. This behavior can be classified as shadowing.

}
}

The resulting behavior can be classified as shadowing; the method variable renders the instance variable inaccessible within the scope of the method. For example, assigning to val from within the method does not affect the value of the instance variable, although assigning to this.val from within the method does.

Compliant Solution (Field Shadowing)

This compliant solution eliminates shadowing by changing the name of the variable defined in the method scope from val to newValue:

Code Block
bgColor#ccccff
class MyVector
Code Block
bgColor#FFcccc

class Vector {
  private int val = 1;
  private void doLogic() {
    int valnewValue;
    //...   
  }
}

Compliant Solution

This solution eliminates shadowing by using a different name for the variable defined in method scope.

Code Block
bgColor#ccccff

private void doLogic() {
  int newValue;
  //...   
}

Noncompliant Code Example

Noncompliant Code Example (Variable Shadowing)

This example is noncompliant because the variable i defined in the scope of the second for loop block shadows the definition of the instance variable i defined in the MyVector class:Method shadowing in different scopes becomes possible when two or more packages are used. Method shadowing is distinct from method overloading as subclasses are allowed to inherit overloadings defined in the base class. It differs from hiding in that the methods do not have to be declared static. It is also distinct from method overriding as exemplified in the following code segment.

Code Block
bgColor#FFcccc

package x;
public class AMyVector {
  voidprivate doLogic()int {i /* print 'A' */ }  // default accessibility= 0;
  public staticprivate void maindoLogic(String[] args) {
    Afor a(i = new y.C();
    a.doLogic(); // invokes doLogic() of class x.B and prints 'B'
  }
}

package x;
public class B extends A {
  void doLogic() { /* print 'B' */ }  // default accessibility
}

package y; // different package
public class C extends x.B {  
  public void doLogic() { /* print 'C' */ } // public
}

Note that class y.C is accessible from the package x and so is its doLogic() method. If however, the main() method defined in class A tries to polymorphically invoke y.doLogic() as shown, the override corresponding to class B in package x will take precedence. This is because the doLogic() methods in classes x.A and x.B are not visible from class y.C due to the default access specifier. As a result, the class x.C is not considered a part of the overriding hierarchy. Notably, the code behaves as expected if the access specifiers of all the methods are changed to public.

Compliant Solution

It is highly recommended that a different name be used so that it is clear that the class residing in another package is not meant to be a part of the overriding chain. A programmer can proceed to invoke methods on it by explicitly using the class name. Even when all the classes define methods with a public access specifier, it is better to avoid reusing names because an evolving class can limit method accessibility anytime in the future causing unexpected results.

0; i < 10; i++) {/* ... */}
    for (int i = 0; i < 20; i++) {/* ... */} 
  }
}

Compliant Solution (Variable Shadowing)

In this compliant solution, the loop counter i is defined in the scope of each for loop block:

Code Block
bgColor#ccccff
class MyVector {
  private
Code Block
bgColor#ccccff

package x;
public class A {
  void doLogic() { /* print 'A' */ }  
  public static voidfor main(String[] args) {
    // explicitly invokes doSequence() of class y.C and prints 'C'
    y.C.doSequence(); 
  }
}

package x;
public class B { int i = 0; i < 10; i++) {/* ... */ }

package y; // different package
public class C extends x.B {  
  public void doSequence() { /* print 'C' */ } // now renamed
}

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

Wiki Markup
\[[JLS 05|AA. Java References#JLS 05]\] 6.3.2 "Obscured Declarations", 6.3.1 "Shadowing Declarations", 14.4.3 "Shadowing of Names by Local Variables"
\[[Bloch 08|AA. Java References#Bloch 08]\] Puzzle 67: All Strung Out
\[[Kabanov 09|AA. Java References#Kabanov 09]\]
\[[Conventions 09|AA. Java References#Conventions 09]\] 6.3 Placement
\[[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

for (int i = 0; i < 20; i++) {/* ... */} 
  }
}

Applicability

Name reuse makes code more difficult to read and maintain, which can result in security weaknesses. An automated tool can easily detect reuse of identifiers in containing scopes.

Automated Detection

ToolVersionCheckerDescription
Parasoft Jtest

Include Page
Parasoft_V
Parasoft_V

CERT.DCL51.HMFDo not give method local variables and parameters the same name as class fields
SonarQube
Include Page
SonarQube_V
SonarQube_V
HiddenFieldCheck


Bibliography

[Bloch 2005]

Puzzle 67, "All Strung Out"

[Bloch 2008]

Item 16, "Prefer Interfaces to Abstract Classes"

[Conventions 2009]

§6.3, "Placement"

[FindBugs 2008]


[JLS 2013]

§6.4.1, "Shadowing"
§6.4.2, "Obscuring"

§7.5.2, "Type-Import-on-Demand Declarations"


...

Image Added Image Added Image AddedSCP02-J. Do not expose sensitive private members of the outer class from within a nested class      04. Scope (SCP)      SCP04-J. Reduce the scope of the SuppressWarnings annotation