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 ;).
One possibility is to factor out the repeated
obj.getSomething()and then collapse the nestedifstatements:To my eye, the result is quite readable, and should no longer trigger the PMD warning.
An alternative is to replace the
Listwith aSet, and avoid the the explicitcontains()checks altogether. Using aSetwould also have better computational complexity.