NPE comparing BigDecimal objects?

After having learned that equals() is not equal enough (my other post) I just replaced equals by compareTo. After studying the Javadoc for BigDecimal.compareTo I did not expect any problems… until some Boundary-value analysis occurred and there the NPE-issue was raised… What a NPE in a simple comparision?

A quick look into the compareTo code showed, what research into the Javadoc confirmed, even though not at the expected place.
The Javadoc for BigDecimal.compareTo(java.math.BigDecimal) did not reveal any pitfalls or precoonditions. Neither did the Javadoc for Comparable.compareTo(T). Nothing about preconditions…
Only in the class-javadoc for Comparable an innocent sentence revealed the source of the problem. Whereas in other places null is just a special case of an Object, Comparable follows this credo:

Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.

So another lesson learned. A pity that this precondition is not documented somewhere. NullPointerException obviously is a RuntimeExcpetion and as such does not need to be documented. But when a method should repsond with such a runtime expcetion to a precondition, this behaviour should be documented as a precondition to the method.

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s