Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

Scope minimization helps developers to avoid common programming errors, improves code readability by tying together connecting the declaration and actual use of a variable, and improves maintainability because unused variables are more easily detected and removed. It may also allow objects to be recovered by the garbage collector more quickly, and it prevents violations of DCL51-J. Do not shadow or obscure identifiers in subscopes.

Noncompliant Code Example

This noncompliant code example shows a variable that is declared outside the for loop. This reduces reusability because the value of the loop index i will have changed after the for statement. Consider, for instance, 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
bgColor#FFcccc

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, even though variable i is not intentionally used outside the for loop. If, for instance, the loop contained , it is declared in method scope. One of the few scenarios where variable i would need to be declared in method scope is when the loop contains a break statement , and the value of i when the loop exits prematurely is inspected, that would be a valid reason for i to be declared local to the method must be inspected after conclusion of the loop.

Compliant Solution

Minimize the scope of variables where possible, for . For example, by declaring declare loop indexes indices within the for statement. :

Code Block
bgColor#ccccff

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

Noncompliant Code Example

This noncompliant code example shows a variable count that is declared outside the counter method. This reduces reusability because , although the variable is not actually used anywhere outside the counter method.

Code Block
bgColor#FFcccc

public class Foo {
  private int count;
  private static private final int MAX_COUNT = 10;

  public void counter() {
    count = 0;
    while (condition()) {
      /* ... */
      if (count++ > MAX_COUNT) {
	    return;
      } 
    }
  }

  private boolean condition() {/* ... *}
  // No other method references count */
  // but several other methods reference MAX_COUNT 
}

Compliant Solution

In this casecompliant solution, the count field is only accessible within declared local to the counter() method.:

Code Block
bgColor#ccccff

public class Foo {
  private static private final int MAX_COUNT = 10;

  public void counter() {
    int count = 0;
    while (condition()) {
      /* ... */
      if (count++ > MAX_COUNT) { 
	    return;
      }
    }
  }
  private boolean condition() {/* ... */}
  // No other method references count 
  */// but several other methods reference MAX_COUNT 
}

Risk Assessment

Using a larger scope than is necessary results in less reliable code.

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

SCP00-J

low

unlikely

medium

P2

L3

...

Applicability

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.

Detecting multiple for statements that use the same index variable is straightforward; it will produce produces false positives in the unusual case where this was intended by the programmer.

Related Guidelines

C Secure Coding Standard: DCL19-C. Use as minimal a scope as possible for all variables and functions

C++ Secure Coding Standard: DCL07-CPP. Use as minimal scope as possible for all variables and methods

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this guideline on the CERT website.

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|http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.4.2], "Scope of Local Variable Declarations"

the value of the index variable is intended to persist between loops.

Bibliography

[Bloch 2001]

Item 29, "Minimize the Scope of Local Variables"

[JLS 2013]

§14.4, "Local Variable Declaration Statements"

 

...

Image Added Image Added Image Added05. Scope (SCP)      05. Scope (SCP)      MET17-J. Do not increase the accessibility of overridden or hidden methods