...
Code Block | ||
---|---|---|
| ||
public class Scope { public static void main(String[] args) { int i = 0; for (i = 0; i < 10; i++) { // Do operations } } } |
Reusability is reduced because the value of the loop index, i
, is modified by the for
statement. Suppose, for example, this code snippet is copied and pasted with the intent to use a different index, j
. If the index-variable change were omitted, the new loop would then attempt to iterate over index i
. Unexpected behavior can result because i
remains in scope.
This code is noncompliant because, even though variable i
is not intentionally used outside the for
loop, it is declared in method scope. One of the few scenarios where variable i
would need to be declared in method scope is when the loop contains a break statement and the value of i
must be inspected after conclusion of the loop.
...
Minimize the scope of variables where possible, for . For example, by declaring declare loop indices within the for
statement:
...
This noncompliant code example shows a variable count
that is declared outside the counter
method, although the variable is not used outside the counter
method. The reusability of the method is reduced because the count
variable would need to be redefined in the new context.
Code Block | ||
---|---|---|
| ||
public class Foo {
private int count;
private static final int MAX_COUNT = 10;
public void counter() {
count = 0;
while (condition()) {
/* ... */
if (count++ > MAX_COUNT) {
return;
}
}
}
private boolean condition() {/* ... *}
// No other method references count
// but several other methods reference MAX_COUNT
}
|
...
Code Block | ||
---|---|---|
| ||
public class Foo { private static final int MAX_COUNT = 10; public void counter() { int count = 0; while (condition()) { /* ... */ if (count++ > MAX_COUNT) { return; } } } private boolean condition() {/* ... */} // No other method references count // but several other methods reference MAX_COUNT } |
...
Detecting multiple for
statements that use the same index variable is straightforward; it produces false positives in the unusual case where this behavior is intended by the programmerthe value of the index variable is intended to persist between loops.
Bibliography
Item 29, "Minimize the Scope of Local Variables" | |
...