Versions Compared

Key

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

...

This noncompliant code example shows a variable that is declared outside the for loop. This reduces reusability because the value of the loop index i will have changed after is modified by the for statement. Consider, for instanceexample, the case when 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 follow because i remains in scope.

...

It should be noted that this code is noncompliant because i is not used outside the for loop. If, for instanceon the other hand, the loop contained a break statement, and the value of i when the loop exits prematurely is inspected, that would be a valid reason for i to i should be declared local to the method.

...

This noncompliant code example shows a variable count that is declared outside the counter method . This reduces reusability because although the variable is not actually used anywhere outside the counter method. This reduces the reusability of the method because count variable would need to be redefined in the new context.

Code Block
bgColor#FFcccc
public class Foo {
  private int count;
  static private final int MAX_COUNT;

  public void counter() {
    count = 0;
    while (condition()) {
      /* ... */
      if (count++ > MAX_COUNT) return;
    }
  }

  /* No other method references count */
}

Compliant Solution

In this casecompliant solution, the count field is only accessible within declared local to the counter method.

Code Block
bgColor#ccccff
public class Foo {
  static private final int MAX_COUNT;

  public void counter() {
    int count = 0;
    while (condition()) {
      /* ... */
      if (count++ > MAX_COUNT) return;
    }
  }

  /* No other method references count */
}

...