HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Cleanly overridable/modifiable compareTo() method?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
modifiablecomparetomethodoverridablecleanly

Problem

Having scoured the web and found little helpful information regarding the implementation of an overridable compareTo() method, I determined myself to find a solution. In another thread I was pointed to some information pertaining to an overridable equals() method, however compareTo() has some pretty unique issues which must be overcome (namely, how to deal with objects of a related supertype, but each existing in a separate hierarchical branch). I've considered many possible scenarios and believe that I've implemented a type which allows for the modification of relational behavior by subtypes, however I'd like external verification that I'm not breaking the compareTo() contract.

```
public abstract class RelationalObject
implements Comparable
{
/*
* Compares two RelationalObjects for semantic ordering.
*
* @param other The RelationalObject to be compared.
*
* @return An int value representing the semantic relationship between the
* two RelationalObjects. A value of 0 is returned if the two
* objects are determined to be equal. A negative value is
* returned if "this" object is determined to have a
* lower semantic ordering than the "other" object. A positive
* value is returned if "this" object is determined to have a
* highter semantic ordering than the "other" object.
*/
public final int compareTo(RelationalObject other)
throws ClassCastException, NullPointerException
{
if (other == null)
throw new NullPointerException("other: Cannot be null.");

int relation = 0;

if (!this.equals(other))
{
if (this.getClass().isAssignableFrom(other.getClass()))
{
if (this.getClass() == other.getClass())
relation = this.compareToExactType(other);
else
/*
* Defer comparison to subtype, thereb

Solution

Nice question! Some thoughts about it:

If B and C are subclasses of A (in separate hierarchical branches) they usually should not know about each other even in the compareToExactType method. It leads to tight coupling which we try to avoid in OOP.

Here the other.compareTo(this) and similar calls seems hard to follow, though ones which would not be the easiest to debug, maintain or to figure out what is the order that it provides in a complex case.

I'd try to use a separate Comparator class which knows all the necessary information about A, B, C and the ordering. You may could use something like that was mentioned in my former answer in the Multi-tiered sorting using custom IComparer question.

Context

StackExchange Code Review Q#14189, answer score: 2

Revisions (0)

No revisions yet.