Search code examples
javajava-8default-method

Why doesn't Delayed provide a default method for compareTo?


The interface Delayed requires any

implementation of this interface [to] define a compareTo method that provides an ordering consistent with its getDelay method.

However I'm wondering, why there isn't a default implementation in Java 8, as compareTo is required by contract to depend solely on getDelay.

Is there a specific reason why this is left for the implementing class? Or is it impossible to create a default method when overwriting a super interface?

Edit: To make my question more understandable, here is an example:

interface Delayed extends Comparable<Delayed> {

    long getDelay(TimeUnit unit);

    @Override
    default int compareTo(Delayed o) {
      // might not be the perfect "compareTo" implementation, but you get the point
      return o == this? 0:
        Long.compare(this.getDelay(TimeUnit.NANOSECONDS), o.getDelay(TimeUnit.NANOSECONDS);
    }

}

Solution

  • The simple answer is that Delayed exists since 1.5 and default methods exist since 1.8. So in order to provide the compareTo method as default method, the interface has to be deliberately changed.

    If that doesn’t happen, there are several possible reasons:

    • It might be that simply no-one ever considered it
    • It might have been considered but dropped because either:

      • There might be possible compatibility issues
      • The expected benefits are not high enough to justify an API change
      • There were things with higher priority to do before the release

    To me, it doesn’t look like a high-priority issue. Most of the time you encounter Delayed implementations in the context of ScheduledExecutorServices provided by the JRE and these implementations already exist and therefore won’t benefit from such a change.

    I don’t think that you will encounter custom Delayed implementations in application code very often, but even if you see it different, the JRE developers obviously decided to focus on additions whose usefulness is more obvious (or less debatable).


    Thinking about it, incorporating the discussion about the getDelay() contract combined with the Comparable contract, it would have been better, if Delayed never extended Comparable at all. After all, it’s not hard to sort objects by a property using a Comparator or similar design pattern.