Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

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 37. DCL51-JG. Do not shadow or obscure identifiers in subscopes.

...

This noncompliant code example shows a variable that is declared outside the for loop. 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. 

Code Block
bgColor#FFcccc
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.

...

In this compliant solution, the count field is declared local to the counter() method:

Code Block
bgColor#ccccff
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 
}

...