‫ DCL02-J. Do not modify the collection's elements during an enhanced for statement

ID: IRCAR201507266

Date: 2015-07-22
 
The enhanced for statement is designed for iteration through Collections and arrays.
The Java Language Specification (JLS) provides the following example of the enhanced for statement in §14.14.2, "The Enhanced for Statement" [JLS 2014]:
 
 
Unlike the basic for statement, assignments to the loop variable fail to affect the loop's iteration order over the underlying set of objects. 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 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 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 integers using an enhanced for loop. It further intends to modify one item in the collection for processing:
 
However, this code does not actually modify the list, as shown by the program's output:
 
Compliant Solution
Declaring i to be final mitigates this problem by causing the compiler to fail to permit i to be assigned a new value:
 
Compliant Solution
This compliant solution processes the "modified" list but leaves the actual list unchanged:
 
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.
 
 
Automated Detection
This rule is easily enforced with static analysis.
 
Reference:
 
 
 


نظرات

بدون نظر
شما برای نظر دادن باید وارد شوید

نوشته

 
تاریخ ایجاد: 6 مرداد 1394

دسته‌ها

امتیاز

امتیاز شما
تعداد امتیازها:0