Scope minimization helps to capture in capturing common programming errors, improves code readability by tying together the declaration and actual use of a variable and eases maintainability because unused variables are easily caught and removed.
Noncompliant Code Example
This noncompliant code 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 unexpected behavior.
| Code Block | ||
|---|---|---|
| ||
public class Scope {
public static void main(String[] args) {
int i = 0;
for(i = 0;i<10; i < 10; i++) {
//do operations
}
}
}
|
...
To be compliant, minimize the scope of variables where possible, such as by declaring loop indexes within the for statement.
| Code Block | ||
|---|---|---|
| ||
public class Scope {
public static void main(String[] args) {
for(int i = 0;i<10; i < 10; i++) { //contains declaration
//do operations
}
}
}
|
...
Using a larger scope than what is necessary results in less reliable code.
...