Scope minimization helps to capture 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.
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 unexpected behavior.
public class Scope {
public static void main(String[] args) {
int i=0;
for(i=0;i<10;i++) {
//do operations
}
}
}
|
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 to perform only one operation if possible. This reduces the need for variables existing in overlapping scopes and consequently, helps prevent errors.
Using a larger scope than necessary results in less reliable code.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
|---|---|---|---|---|---|
SCP00- J |
low |
unlikely |
medium |
P2 |
L3 |
TODO
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
\[[JLS 05|AA. Java References#JLS 05]\] [Section 14.4.2, Scope of Local Variable Declarations|http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.4.2] \[[Bloch 01|AA. Java References#Bloch 01]\] Item 29, Minimize the scope of local variables |
05. Scope (SCP) 05. Scope (SCP) SCP01-J. Do not increase the accessibility of overridden or hidden methods