2

Possible Duplicate:
What is the reason for these PMD rules?

Why do I get DD/DU warnings?

Here's my code:

// DD warning from PMD
public Object foo() {
  Object result = null;
  if (condition) {
    // code block, no accec to result
    result = newResult;
  }
  return result;
}
// DU warning from PMD
List<Object> data = new ArrayList<Object>(anotherList);
anotherList.remove(1);
// some other modification of anotherList
if (condition) {
  // some code. no access to data
  for (Object o : data) {
    // loop for original content of the list
  }
}

Is there something wrong here? Or is it a PMD bug? Can I ignore these warnings?

Linus Fernandes
  • 498
  • 5
  • 30
Sergiy Medvynskyy
  • 11,160
  • 1
  • 32
  • 48

1 Answers1

4

Your DD anomaly can indeed be written better, with less chance of bugs:

return condition? newResult : null;

or, if you are more conservative regarding syntax,

if (condition)
  return newResult;
return null;

In the second example you are creating data unconditionally, but using it only conditionally. Rewrite to

if (condition) {
  List<Object> data = new ArrayList<>(anotherList);
  // or maybe just use anotherList without copying
  ...
}
else {
  anotherList.remove(1);
  // some other modifications of anotherList
}
Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
  • First proposal for DD anomaly cannot be implemented because newResult is computed in the block. Second - provokes another PMD rule voilation (multiple exit from method). Proposal for DU causes code duplication. – Sergiy Medvynskyy Jan 18 '13 at 10:02
  • I'll take your word for it; it's not part of your question. Anyway, this answers your question: it is not a bug with PMD. – Marko Topolnik Jan 18 '13 at 10:06