Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 857
Farrukh Chishti Avatar asked Mar 01 '13 07:03

Farrukh Chishti


1 Answers

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.

like image 122
Jon Skeet Avatar answered Oct 30 '22 08:10

Jon Skeet