Search code examples
javaforeachfinalpmd

PMD violation on for each loop (final or not?)


I just recently found out about PMD and want to improve my code with it. Therefore I have enabled all rules (and got 47000 violations :P). Anyway, I have a problem with this one:

double mean = 0;
for (int p : points)
  mean += full[1][p];
mean /= points.size();

On the for each loop, PMD tells me that Local variable 'p' could be declared final. If I change it to

double mean = 0;
for (final int p : points)
  mean += full[1][p];
mean /= points.size();

it tells me to Avoid using final local variables, turn them into fields. The second violation doesn't really make sense to me. What is the "correct" way to do this? (I realize that there may be different ways, I just want to know how PMD would like it to be.)


Solution

  • I think you found an inconsistency in pmd's rules, when following one of the rules makes you violate another rule.

    I think the first loop is fine as is: the second loop works fine, too, but using final there is rather unorthodox. Adding a final there without a good cause+ could trip up even very experienced developers. Since you do not want to make reading your program any harder than it is, I'd recommend skipping the final in foreach loops.


    + Making the loop variable available to an anonymous class is one such good cause.