Skip to content
Advertisement

Is it OK to add default implementations to methods of an interface which represents a listener?

There is a certain library I use in my project. This library has an interface which has about 15 methods.

The purpose of this interface is to make it possible to subscribe for some events that are generated in the library. A listener class in application can implement this interface and register itself as a listener in the library to receive events.

All the methods in this interface are actually events. There can be listeners who only need to receive only one or two events from many events in the interface. Even though a listener is only interested in few events, listener has to implement all the methods when extending the interface.

So I asked the developer of this library to add empty default implementations to the methods in the interface.

But the library developer refuses to add default implementations, stating that it would violate java best practices and using default implementations in interface methods go against the purpose of interfaces.

But, as I can understand, a method in this interface does not specify some action which an implementer of this interface should be capable of. A method in this interface rather defines an event which an implementer may be interested in. So I can’t see a clear reason for not adding default implementations.

So, is adding default implementations to this interface break the java best practices?

Advertisement

Answer

But the library developer refuses to add default implementations, stating that it would violate java best practices and using default implementations in interface methods go against the purpose of interfaces.

This argument was valid until default interface methods were introduced. Now your colleague would have to argue that the JLS of Java 8 perverted interfaces and the JDK now contains classes which go against the purpose of interfaces. Still this is a viable extreme standpoint but fruitless.

You simply can avoid the discussion by deriving an own interface from the library interface and providing default empty implementations for all inherited methods.

public interface MyInterface extends LibraryInterface {
    @Override default public void event1() {
    }

    ...
}

Or you both can review the following design which seems dubious to me and which led to your discussion about default method in interfaces:

Even though a listener is only interested in few events, listener has to implement all the methods when extending the interface.

A solution could be to simply split up the big interface in many smaller ones.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement