Farrukh Chishti
Farrukh Chishti

Reputation: 8437

Inevitable DD anomaly in PMD

I came across a special case where i am unable to solve the DD anomaly in PMD. Suppose the code is :

BigDecimal amount = BigDecimal.ZERO;
for(int i=0;i<5;i++)
{
      amount = amount.add(i);
}
return amount;

On running this code through PMD, it will show a DD anomaly at declaration of amount. However if i remove the initialization i will get an exception.How can this situation pass through PMD. Anyone?

Upvotes: 5

Views: 8467

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500225

From the "controversial rules" page, DataflowAnomalyAnalysis section:

DD - Anomaly: A recently defined variable is redefined. This is ominous but don't have to be a bug.

In this case, it's definitely not a bug. I suggest you suppress or ignore the warning for this specific case. (The fact that the original value is used when calculating the next value suggests the rule could have been written better, to be honest.)

It's very important that you understand the reasons for rules and pick and choose which rules you obey and where. For example, I strongly disagree with the "only one exit point" rule - there are plenty of times that having more than one exit point makes a method significantly simpler to read. Be selective, and if a rule is normally fine but you've verified that your code is okay in this specific case, suppress the warning just in that one place.

Upvotes: 12

Related Questions