Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Changed some wording.

...

This noncompliant example shows a variable that is declared outside the for loop. This can harm reusability as the loop index i will change after the for statement. Consider for instance, the case when this code snippet is copy pasted with the intent of using a different index j but the statement mistakenly still iterates over index i. As i is still in scope, this will lead to a rather obtuse outcomeunexpected behavior.

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

...

Additionally, methods should be designed for to perform only one operation if possible. This simplicity avoids reduces the need for variables from existing in overlapping scopes and therefore helps prevents errors.

Risk Assessment

...