...
This code is noncompliant because even though variable i
is not intentionally used outside the for
loop. The , it is declared in method scope. One of the few scenarios where variable i
would need to be declared local to the method if, for example, in method scope is when the loop contained contains a break statement and the value of i
was inspected outside must be inspected after conclusion of the loop.
Compliant Solution
...
Code Block | ||
---|---|---|
| ||
public class Scope {
public static void main(String[] args) {
for (int i = 0; i < 10; i++) { // contains declaration
// Do operations
}
}
}
|
...
Code Block | ||
---|---|---|
| ||
public class Foo { private int count; private static private final int MAX_COUNT = 10; public void counter() { count = 0; while (condition()) { /* ... */ if (count++ > MAX_COUNT) { return; } } } //* No other method references count */ /*/ but several other methods reference MAX_COUNT */ } |
Compliant Solution
In this compliant solution, the count
field is declared local to the counter
method.
Code Block | ||
---|---|---|
| ||
public class Foo { private static private final int MAX_COUNT = 10; public void counter() { int count = 0; while (condition()) { /* ... */ if (count++ > MAX_COUNT) { return; } } } /*/ No other method references count */ //* but several other methods reference MAX_COUNT */ } |
Applicability
Detecting local variables that are declared in a larger scope than is required by the code as written is straightforward and can eliminate the possibility of false positives.
...