07:31:44 pm on January 16, 2010 | # |
Beware of implementing Java Comparable.Here is why…
When implementing compareTo() the normal inclination is to provide the real difference (negative or positive) when a match is not found. Today this lead to a subtle bug which was only discovered when the software was tested over a very large data-set.
What happened: Comparing Long and providing the difference as int (return type of compareTo) is a potential sand trap. As positive Integer can only be up to 2 billion, anything beyond that and it silently turns it into a negative integer!
Bottomline: Simply return +1 or -1 as appropriate when a match is not found.
How we discovered the bug: Through high volume of unit testing using random data over the entire data range (2^32 - 1).
Leave a Comment
You must be logged in to post a comment.