A trapdoor in Apache Commons CollectionUtils (and its docs)

A few days ago I hit a problem while refactoring some legacy Java Code. Following my own advice to use safe and simpler library methods I changed the code-block

List<String> list = dao.getEntries(id);
if(list != null && list.size() > 1) {
  doFancyLogic(list);
}

to

List<String> list = dao.getEntries(id);
if(CollectionUtils.size(list) > 1) {
  doFancyLogic(list);
}

Should do the same, looks nicer and should be safer too, right? Imagine my confusion when suddenly several unit tests began failing at other parts of the code not directly related to this change. When I found out that this single line was the cause of the other errors I of course looked up the JavaDoc for CollectionUtils on Google. According to the docs at http://commons.apache.org/collections/apidocs/org/apache/commons/collections/CollectionUtils.html the size() method should return 0 when presented with a null collection. Things were very strange here. In fact, it took me a few days to find out what's wrong.

In fact, I did not recognize that the access to the JavaDoc was redirected to https://commons.apache.org/proper/commons-collections//apidocs/org/apache/commons/collections/CollectionUtils.html, which did not show the documentation of the latest stable CollectionUtils docs (as it did until a few weeks ago) but showed the version of the SVN tip. It took a roundtrip through the Apache Commons main page to find the correct JavaDoc page for the current stable 3.2.1 CollectionUtils at https://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections/CollectionUtils.html. And, surprise surprise, there the API for the size() method looks a bit different: "Throws: java.lang.IllegalArgumentException - thrown if object is not recognised or null".
Well, so much for the praised null-safety of Apache Commons... In the current implementation, CollectionUtils.size() is of no use for me and I reverted the refactoring.

In the end I was a victim of partly my own assumptions for the null-safety of Apache Commons and partly a very weird redirection of the Google search result URL. I still have no idea why this URL suddenly gets redirected to a different version than it did until a few weeks ago but I hope that either Google soon updates its search result (unlikely as there are loads of references to this address) or Apache corrects it to its former destination. For the safety of users in my opinion the correct version which shows up should be the one of the latest stable version, not an arbitrary SVN version.

Lesson learned: also check version of JavaDoc if something smells fishy, even if it has been correct in the past.

|

Similar entries