Addition to Comparable interface (original) (raw)

Roy van Rijn roy.van.rijn at gmail.com
Tue Mar 31 03:56:03 PDT 2009


AUTHOR(S): Roy van Rijn

OVERVIEW

Currently the interface Comparable only has one method: int compareTo(Object o);

This is perfect and enough to work with. But the 'int' you have to return is a bit messy and unclear.

FEATURE SUMMARY:

The return value of the Comparable interfae could be made a lot clearer if it would have the following static variables: public static int BEFORE = -1; public static int EQUAL = 0; public static int AFTER = 1;

MAJOR ADVANTAGE:

Its much more clear what you need to return when you are implementing the Comparable interface. The addition won't affect any previously written code and won't break backwards compatibility..

MAJOR BENEFIT:

Readability of the code where the interface is used.

MAJOR DISADVANTAGE:

The interface becomes a little bit larger.

ALTERNATIVES:

Another alternative would be to use an enum. This would be even clearer but would break backwards compatibility.

EXAMPLE:

Comparing humans by age and name (in case the age is equal):

public int compareTo(Object otherHuman) { if(this == otherHuman) { //Same object? Then we are equal return EQUAL; } else if(otherHuman==null || otherHuman.getName() == null) { //Other human has null values, we need to go after return AFTER; } else if(this.getName() == null) { //We have null values, we go before other human return BEFORE; } else if(this.getAge != otherHuman.getAge()) { //If the age isn't the same, compare by age: return this.getAge() - otherHuman.getAge(); } else { //Finally compare by name return this.getName().compareTo(otherHuman.getName()); } }

This is clearer then: .... if(this == otherHuman) { //Same object? Then we are equal return 0; } else if(otherHuman==null || otherHuman.getName() == null) { //Other human has null values, we need to go after return 1; } else if(this.getName() == null) { //We have null values, we go before other human return -1; ....

DETAILS: SPECIFICATION:

Specification and details are clear, just add this to Comparable: public static int BEFORE = -1; public static int EQUAL = 0; public static int AFTER = 1;

COMPILATION: Trivial. TESTING: Trivial. LIBRARY SUPPORT: No. REFLECTIVE APIS: No. OTHER CHANGES: Maybe implementing classes can be refactored to use this feature, optional. MIGRATION: No. COMPATIBILITY: No issues. BREAKING CHANGES: No. EXISTING PROGRAMS: Same, no changes.



More information about the coin-dev mailing list