I recently stumpled upon the following warning using PMD (embedded in hudson), my code seems to suffer CollapsibleIfStatements, which I do not fully understand. The code looks like this
// list to be filled with unique Somethingness
List list = new ArrayList();
// fill list
for (SomeObject obj : getSomeObjects()) { // interating
if (!obj.getSomething().isEmpty()) { // check if "Something" is empty *
if (!list.contains(obj.getSomething())) { // check if "Something" is already in my list **
list.add(obj.getSomething()); // add "Something" to my list
}
}
}
In my opinion this code isn't more "collapsible" (otherwise it would be even more unreadable for the next guy reading the code). On the other hand I want solve this warning (without deactivating PMD ;).
I think this is what PMD wants:
Here are few tips for improvements (and preventing PMD to scream):
Extract variable:
Extract method in
Something
(much more OOD):and replace the whole condition with simple:
It is collapsible:
IMHO, this check can be useful sometimes, but should be ignored in some other cases. The key is to have code as readable as possible. If you feel that your code is more readable than a collapsed if statement, then add a
@SuppressWarnings("PMD.CollapsibleIfStatements")
annotation.One possibility is to factor out the repeated
obj.getSomething()
and then collapse the nestedif
statements:To my eye, the result is quite readable, and should no longer trigger the PMD warning.
An alternative is to replace the
List
with aSet
, and avoid the the explicitcontains()
checks altogether. Using aSet
would also have better computational complexity.