I've discovered three or four (maybe five, if you want to divide up every possible detail) cases where the isEmpty rule should detect an equivalent syntax but does not.
1) Checking if size() is less than 1. (As far as I am aware size() cannot return negatives; if it can, then obviously this check would have different implications, perhaps deserving a rule of its own if they are undesirable implications.)
2) Checking if size() greater than 0 (or less then 1) with the number on the left side of the comparison.
3) Checking size() on a newly instantiated collection or on the return value of a function that returns a collection (both non-variables).
Example code below:
import java.util.ArrayList; public class TestIsEmpty { public static void main(String args[]) { ArrayList<String> testObject = new ArrayList<String>(); // These ones are flagged // if (testObject.size() == 0) { // System.out.println("List is empty"); // } // if (testObject.size() != 0) { // System.out.println("List is empty"); // } // if (0 == testObject.size()) { // System.out.println("List is empty"); // } // if (0 != testObject.size()) { // System.out.println("List is empty"); // } // if (testObject.size() > 0) { // System.out.println("List is empty"); // } // These ones are not flagged if (testObject.size() < 1) { System.out.println("List is empty"); } if (0 < testObject.size()) { System.out.println("List is empty"); } if (1 > testObject.size()) { System.out.println("List is empty"); } if (new ArrayList().size() == 0) { System.out.println("New list starts empty"); } if (GetArrayList().size() == 0) { System.out.println("List returned from function is empty"); } } public static ArrayList<String> GetArrayList() { return new ArrayList<String>(); } }
This should get five results, but gets none:
pmd -d TestIsEmpty.java -R java-design/UseCollectionIsEmpty
This will be fixed with the next release.
However, it probably won't cover all the cases you have in mind. I extended it to discover simple method calls like in the test case. But if the method is defined in another class, PMD doesn't know about the return type of the method at the moment, so it can't determine whether the size() method of a collection is called or not.