Rich Interfaces In Java

One of the new features added to Java 8 is default methods. In previous versions of Java, adding a new method to an interface would break existing implementations. This made it very hard to evolve your public API without disrupting your clients. Java 8 now allows implementations of methods in an interface. This was needed because Java 8 introduced many new methods on existing interfaces such as sort in List or stream in Collection .

Thin versus rich interfaces

When creating an interface you face a trade-off in either making it rich or thin. A rich interface has many methods which makes it convenient for the caller while a thin interface has only a few methods which makes it easy to implement but not quite as useful for the caller.

Traditionally Java interfaces have been thin rather than rich. Scala, on the other hand, has traits which allow concrete implementations and so tend to be very rich. Now that Java 8 has default methods we can take the same rich interface approach in our Java code as Scala does with traits.

To create a rich interface, define a small number of abstract methods and a large number of concrete methods defined in terms of the abstract methods. Implementors of your interface need only implement the thin abstract part of your interface and thereby gain access to the richer part without having to write any more code.

An example

As a simple example I have implemented the Rational class and Ordered trait from the Programming in Scala book. We don’t get the symbolic method names and implicit conversions but the rich interface concept remains the same.

Here is our rich Ordered interface. It declares one abstract method compare but also implements a number of convenience methods in terms of this abstract method.

Here is our Rational class which implements Ordered. Apart from overriding equals and hashCode, the only method we need to implement is compare and we get lessThan, greaterThan, lessThanOrEqual, greaterThanOrEqual and compareTo “for free”.

Here’s a unit test that exercises the class.

This is a very simple example but shows how we can introduce Scala’s rich interface style of traits into our Java 8 code.

Leave a Reply +

Leave a Reply

Your email address will not be published. Required fields are marked *