Java for each loop being flagged as UR anomaly by PMD
It appears that you have hit a bug in PMD. The DataflowAnomalyAnalysis rule does not seem to catch all possible kinds of variable definitions (another example found here). UR stands for "undefined reference", which is obviously incorrect.
So, what can you do?
Since the problem appears to affect mostly the UR part of the rule, you can disable it and continue using the DU and DD parts. You need a fairly recent version of PMD to do this. In your ruleset file, suppress UR findings like this:
<rule ref="rulesets/java/controversial.xml/DataflowAnomalyAnalysis">
<properties>
<property name="violationSuppressRegex" value="^Found 'UR'-anomaly.*"/>
</properties>
</rule>
Update: For PMD 6.+, the rule ref has changed (thanks ZuziaKru):
<rule ref="category/java/errorprone.xml/DataflowAnomalyAnalysis">
<properties>
<property name="violationSuppressRegex" value="^Found 'UR'-anomaly.*"/>
</properties>
</rule>
In my humble opinion, the whole UR checking is a bit over the top, because the compiler will not accept undefined references. And these days, running the compiler is no longer such a big deal.
Please see, appropriate PMD rule DataflowAnomalyAnalysis constantly is considered controversial. I personally caught it on completely crazy detection of almost any type of anomaly:
- Any inline declaration leads to UR anomaly alerted. This includes variables defined in
for
loop scope. - DU anomaly often is alerted if variable is defined out of loop scope and its value is changed inside loop before end of some local scope.
- DD anomaly is reported often in parallel with wrong UR or DU detected. In addition it may be reported if we setup variable before loop and then update it's value inside loop (for next iteration). This anomaly is referenced even inside rule description to be not so relevant.
So by my opinion it is worth to turn off this buggy rule at all.