...
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.
...
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 not more than one time.
Code Block | ||
---|---|---|
| ||
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 |
---|---|---|---|---|---|
DCL05 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="1b4f89c193aeb0e5-29c203a8-47454dc9-b566a629-fd94bc4504fd4f42fad5d7e2"><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> |
...