The enhanced for
statement introduced in Java 5 (also known as the for-each idiom) is primarily used for iterating over collections of objects. Unlike the original for
statement, assignments to the loop variable fail to affect the loop's iteration order over the underlying set of objects. Consequently, assignments to the loop variable can have an effect other than what is intended by the developer. This provides yet another reason to avoid assigning to the loop variable in a for
loop.
As detailed in §14.14.2, "The Enhanced For Statement" of the Java Language Specification [[JLS 2005]]
an enhanced
for
statement of the formfor (ObjType obj : someIterableItem) { // ... }is equivalent to a standard
for
loop of the formfor (Iterator myIterator = someIterableItem.iterator(); iterator.hasNext();) { ObjType obj = myIterator.next(); // ... }
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.
Declare all enhanced for
statement loop variables to be 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.
Collection<ProcessObj> processThese = // ... for (ProcessObj processMe: processThese) { if (someCondition) { // found the item to skip someCondition = false; processMe = processMe.getNext(); // attempt to skip to next item } processMe.doTheProcessing(); // process the object }
The attempt to skip to the next item appears to succeed because the assignment is successful, and the value of processMe
is updated. Unlike an original for
loop, however, the assignment leaves the overall iteration order of the loop unchanged. As a result, the object following the skipped object is processed twice.
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 no more than one time.
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.
Rule |
Severity |
Likelihood |
Remediation Cost |
Priority |
Level |
---|---|---|---|---|---|
DCL02-J |
low |
unlikely |
low |
P3 |
L3 |
Automated Detection
This rule is easily enforced with static analysis.
Bibliography
<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="8026b490-dcac-4a88-b13f-c3373e036986"><ac:plain-text-body><![CDATA[ |
[[JLS 2005 |
AA. Bibliography#JLS 05]] |
[§14.14.2,"The enhanced for statement" |
http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.2] |
]]></ac:plain-text-body></ac:structured-macro> |
01. Declarations and Initialization (DCL) 02. Expressions (EXP)