Scope minimization helps developers to avoid common programming errors, improves code readability by connecting the declaration and actual use of a variable, and improves maintainability because unused variables are more easily detected and removed.
...
This noncompliant code example shows a variable that is declared outside the for
loop. This reduces reusability Reusability is reduced because the value of the loop index, i
, is modified by the for
statement. ConsiderSuppose, for example, the case when this code snippet is copied and pasted with the intent to use a different index, j
. If the index variable change were omitted, the new loop would then attempt to iterate over index i
. Unexpected behavior can 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 } } } |
It should be noted that this This code is noncompliant because i
is not used outside the for
loop. The variable i
would need to be declared local to the method if, for example, the loop contained a break statement and the value of i
was inspected outside the loop.
...
This noncompliant code example shows a variable count
that is declared outside the counter
method, although the variable is not used outside the counter
method. This reduces the reusability of the method because the count
variable would need to be redefined in the new context.
...
Detecting local variables that are declared in a larger scope than is required by the code as - written code is straightforward and can avoid any eliminate the possibility of false positives.
...
C Secure Coding Standard: "DCL19-C. Minimize the scope of variables and functions"
C++ Secure Coding Standard: "DCL07-CPP. Minimize the scope of variables and methods"
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="7d1efdb251228407-8bdd1fcf-47a74633-b34ab9e9-9d95fd2920994263155f4ec3"><ac:plain-text-body><![CDATA[ | [[Bloch 2001 | AA. References#Bloch 01]] | Item 29, Minimize the scope of local variables | ]]></ac:plain-text-body></ac:structured-macro> | |
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="41b14e0d1da07d70-f6be82e0-474d4613-b169ac84-decea133f3cb1284310baa6c"><ac:plain-text-body><![CDATA[ | [[JLS 2005 | AA. References#JLS 05]] | [§14.4.2, "Scope of Local Variable Declarations" | http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.4.2] | ]]></ac:plain-text-body></ac:structured-macro> |
...