Versions Compared

Key

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

...

Minimize the scope of variables where possible, for example, by declaring loop indices within the for statement.:

Code Block
bgColor#ccccff
public class Scope {
  public static void main(String[] args) {
    for (int i = 0; i < 10; i++) { // Contains declaration
      // Do operations
    }
  }
}

...

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. This reduces the The reusability of the method is reduced because the count variable would need to be redefined in the new context.

...

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 
}

...

Detecting multiple for statements that use the same index variable is straightforward; it will produce produces false positives in the unusual case where that this was behavior is intended by the programmer.

...