You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

Scope minimization helps to capture common programming errors, improves code readability by tying together the declaration and actual use and eases maintainability since unused variables are easily caught and removed.

Non-Compliant Code Example

This non-compliant example shows a variable that is declared outside the for loop. This can harm reusability since the loop index i will change after the for statement. Consider for instance, if this code snippet is copy pasted with the intent of using a different index j but the statement mistakenly still iterates over index i. Since i is still in scope, this will lead to a rather obtuse outcome.

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

Compliant Solution

To be compliant, minimize scope where possible, such as by declaring loop indexes within the for statement.

public class Scope {
  public static void main(String[] args) {
    for(int i=0;i<10;i++) { //contains declaration
    	//do operations
    }
  }
}

Additionally, methods should be designed for only one operation if possible. This simplicity avoids variables from existing in overlapping scopes.

References

EJPLG Item 29, Minimize the scope of local variables
JLS 14.4.2 Scope of Local Variable Declarations

  • No labels