Let’s compare

Recently I was writing code where I compared Enum’s to each other for an if-statement. It looked something like this

if(enumConstant1.compareTo(enumConstant2) <= 0) {
// more code

Giving the code a second look, I was rather unhappy that you could not immediately see what was going on here. You had to puzzle your brains what the compareTo method of the Comparable interface had specified over itself. Ofcourse, after reading the javadoc of the method it all made sense. But still I asked myself, am I interested here in a comparison?
No, I want to know if a certain condition is valid! If you give it a quick look, you see something comparing against zero. What is going on ?

I decided to make a substition for the compareTo method, which has more emphasis on conditions. I created the Operand interface ( an Operand is mathematically an entity in a comparison ) which has the same functionality as the compareTo method of the Compage interface, but delivers better readable methods.

Now the code reads

// more code

Instantly, you can see that for which condition the if-branch is followed. I turned my effort into a small Google Code project, easycomparator, where you also can take a look at the code. If you desire you can include the jar as a Maven dependency. You can retrieve the jar, source and javadoc from http://artifactory.cybersnippet.nl:8080 login in as ‘anonymous’.

About the author

haiko By Haiko van der Schaaf Google