Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Changed title, plus a few small grammar changes

...

Consequently, an assignment to the loop variable is equivalent to modifying a variable local to the loop body whose initial value is the object referenced by the loop iterator. This modification is not necessarily erroneous, but it can obscure the loop functionality or indicate a misunderstanding of the underlying implementation of the enhanced for statement.

All Declare all enhanced for statement loop variables should to be declared as final. The final declaration causes Java compilers to flag and reject any assignments made to the loop variable.

Noncompliant Code Example

This noncompliant code example attempts to process a collection of objects using an enhanced for loop. It further intends to skip processing one item in the collection.

...

Note that if processMe were declared final, a compiler error would result at the attempted assignment.

Compliant Solution

This compliant solution correctly processes the objects in the collection at most once.

Code Block
bgColor#ccccff
Collection<ProcessObj> processThese = // ... 

for (final ProcessObj processMe: processThese) {
  if (someCondition) { // found the item to skip
    someCondition = false;
    continue; // skip by continuing to next iteration
  }
  processMe.doTheProcessing(); // process the object
}

Risk Assessment

Assignments to the loop variable of an enhanced for loop (for-each idiom) fail to affect the overall iteration order, lead to programmer confusion, and can leave data in a fragile or inconsistent state.

Guideline

Severity

Likelihood

Remediation Cost

Priority

Level

DCL05-J

low

unlikely

low

P3

L3

Automated Detection

Easily enforced with static analysis.

Related Vulnerabilities

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

Bibliography

Wiki Markup
\[[JLS 2005|AA. Bibliography#JLS 05]\] Section [14.14.2|http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.2] "The enhanced for statement"

...