Scope minimization helps developers avoid common programming errors, improves code readability by connecting the declaration and actual use of a variable, and improves maintainability because unused variables are more easily detected and removed. It may also allow objects to be recovered by the garbage collector more quickly, and it prevents violations of 373. DCL51-JG01. Do not shadow or obscure identifiers in subscopes.
Noncompliant Code Example
This noncompliant code example shows a variable that is declared outside the for
loop.
...
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.
Compliant Solution
Minimize the scope of variables where possible, for example, by declaring loop indices within the for
statement:
Code Block | ||
---|---|---|
| ||
public class Scope { public static void main(String[] args) { for (int i = 0; i < 10; i++) { // Contains declaration // Do operations } } } |
Noncompliant Code Example
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; } } } // 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 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.
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 programmer.
Bibliography
Item 29, "Minimize the Scope of Local Variables" | |
[JLS 2011] |
...