Monday, June 7, 2010

If a bug exists long enough it becomes a feature..

Consider the following code which uses a java.util.TreeSet:

1 TreeSet set = new TreeSet();
2 set.add(null);
3 set.remove(null);

Does it work? Does it throw a NullPointerException? If we look at the javadoc of the TreeSet.add method we read:

  * @throws NullPointerException if the specified element is null
 *         and this set uses natural ordering, or its comparator
 *         does not permit null elements

As we create the TreeSet using the default constructor it uses the natural ordering and we would expect a NullPointerException on line 2. However, the NullPointerException happens only on line 3. Even though this is a clear bug which got reported already for java 1.3 (issue 5045147) it is still present in Java 6. Sun decided that there is too much code that would break if they fixed the bug that adding null to an empty TreeSet is allowed. One might ask what quality such code has..

No comments:

Post a Comment