...
This noncompliant code example reuses the name of the val
instance field in the scope of an instance method. This behavior can be classified as shadowing.
...
Compliant Solution (Field Shadowing)
This compliant solution eliminates shadowing by changing the name of the variable defined in method scope.
...
Code Block | ||
---|---|---|
| ||
for (int i = 0; i < 10; i++) { } for (int i = 0; i < 20; i++) { } |
...
Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
SCP02-J | low | unlikely | medium | P2 | L3 |
Automated Detection
Wiki Markup |
---|
An automated tool can easily detect reuse of names whose earlier definition appears somewhere in the Java include path. FindBugs, for example, detects at least four sub-instances of this guideline \[[FindBugs 2008|AA. Bibliography#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
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
...
Wiki Markup |
---|
\[[JLS 2005|AA. Bibliography#JLS 05]\] [Section 6.3.2|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.3.2] "Obscured Declarations", [Section 6.3.1|http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.3.1] "Shadowing Declarations", [Section 7.5.2|http://java.sun.com/docs/books/jls/third_edition/html/packages.html#7.5.2] "Type-Import-On_Demand Declaration", [Section 14.4.3|http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.4.3] "Shadowing of Names by Local Variables"
\[[Bloch 2005|AA. Bibliography#Bloch 05]\] Puzzle 67: All Strung Out
\[[Bloch 2008|AA. Bibliography#Bloch 08]\] Item 16: Prefer interfaces to abstract classes
\[[Kabanov 2009|AA. Bibliography#Kabanov 09]\]
\[[Conventions 2009|AA. Bibliography#Conventions 09]\] 6.3 Placement
\[[FindBugs 2008|AA. Bibliography#FindBugs 08]\]: |
...
...
MET17-J. Do not increase the accessibility of overridden or hidden methods OBJ17-J. Do not expose sensitive private members of an outer class from within a nested class