The enhanced for statement introduced in Java 1.5 , commonly referred to as (a.k.a. the for-each idiom, ) is primarily used for iterating over collections of objects. While similar to Unlike the original for statement, assignments to the loop variable do not modify the collection of objects over which the loop iterates. Assignments fail to affect the loop's iteration order over the underlying set of objects. Thus, assignments to the loop variable may not have the an effect other than that intended by the developer and should be avoided. This provides yet another reason to avoid assigning to the loop variable in a for loop.
Wiki Markup |
---|
As detailed in the Java Language Specification \[[JLS 2005|AA. Bibliography#JLS 05]\], Section 14.14.2, "The enhanced {{for}} statement", an enhanced {{for}} statement of the form |
Code Block |
---|
for (ObjType obj : someIterableItem) { // ... } |
is equivalent to a standard for loop of the form
Code Block |
---|
for (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 that referenced by the loop iterator refers to. While this This modification is not necessarily erroneous, it but may obscure the loop functionality or indicate a misunderstanding of the underlying implementation of the enhanced for statement.
It is recommended that Declare all enhanced for statement loop variables be declared as final. The final declaration causes Java compilers to flag and reject any assignments made to the loop variable, from within the loop body.
Noncompliant Code Example
This noncompliant code example attempts to initialize a Character
array process a collection of objects using an enhanced for loop. However, because assignments to the loop variable do not modify the array over which the loop iterates, the array is not suitably initializedIt further intends to skip processing one item in the collection.
Code Block | ||
---|---|---|
| ||
Character[]Collection<ProcessObj> arrayprocessThese = new Character[10];// ... for (CharacterProcessObj cprocessMe: arrayprocessThese) { cif = 'x';(someCondition) { // initialization attempt for(int i=0;i<array.length;i++) System.out.print(array[i]); // prints 10 "null" values 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 is "successful" in the sense that the assignment succeeds and the value of processMe
is updated. Unlike an original for loop, however, the assignment leaves the overall iteration order of the loop unchanged. Thus, the object following the skipped object is processed twice; this is unlikely to be what the programmer intended.
Note that if processMe
were declared final, a compiler error would result at the attempted assignmentNote that if c
is declared final
, a compiler error results when an attempt is made to initialize it.
Compliant Solution
This compliant solution correctly initializes the array using a for
loopprocesses the objects in the collection at most once.
Code Block | ||
---|---|---|
| ||
Character[]Collection<ProcessObj> arrayprocessThese = new Character[10];// ... for (intfinal iProcessObj = 0; i < array.length; i++) array[i] = 'x'; for(final Character c: array) System.out.print(c); // prints 10 "x" values |
Risk Assessment
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 Attempts to assign to the loop variable from within the enhanced for loop (for-each idiom) are futile fail to affect the overall iteration order, lead to programmer confusion, and may leave the class data in a fragile , or inconsistent state.
Guideline | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL05-J | low | unlikely | low | P3 | L3 |
Automated Detection
TODOEasily enforced with static analysis.
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this guideline on the CERT website.
Other Languages
TODO
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" |
...