Scope minimization helps in capturing developers to avoid common programming errors, improves code readability by tying together the declaration and actual use of a variable, and eases improves maintainability because unused variables are more easily caught detected and removed.
Noncompliant Code Example
This noncompliant code example shows a variable that is declared outside the for
loop. This can harm reusability as reduces reusability because the value of the loop index i
will change have changed after the for
statement. Consider for instance, the case when this code snippet is copy copied and pasted with the intent of using to use a different index j
but the statement mistakenly still iterates . If index variable change is omitted, the new loop would then attempt to iterate over index i
. As i
is still in scope, this will lead to a unexpected behaviorUnexpected behavior may follow because i
remains in scope.
Code Block | ||
---|---|---|
| ||
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 Minimize the scope of variables where possible, such as for example by declaring loop indexes within the for
statement.
...
Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
SCP00-J | low | unlikely | medium | P2 | L3 |
Automated Detection
Detecting local variables that are declared in a larger scope than is required by the as-written code is straightforward, and can avoid any possibility of false positives.
Detecting multiple for
statements that use the same index variable is straightforward; it will produce false positives in the unusual case where this was intended by the programmer.TODO
Other Languages
This guideline appears in the C Secure Coding Standard as DCL19-C. Use as minimal a scope as possible for all variables and functions.
...
Bibliography
Wiki Markup |
---|
\[[Bloch 2001|AA. Bibliography#Bloch 01]\] Item 29, Minimize the scope of local variables \[[JLS 2005|AA. Bibliography#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 2001|AA. Bibliography#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