Java – is it OK to add the default implementation to the method representing the listener’s interface?

A library is used in my project This library has an interface with about 15 methods

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

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

So I asked the developers of this library to add an empty default implementation to the methods of the interface

However, the library developers refused to add the default implementation, pointed out that it would violate Java best practices, and used the default implementation in the interface method to achieve the purpose of the interface

However, as I can understand, a method in this interface does not specify some operations that the implementer of this interface should be able to perform One method in this interface is to define an event that the implementer may be interested in, so I can't see the clear reason why the default implementation is not added

So, adding a default implementation to this interface breaks Java best practices?

Solution

This parameter is valid before the default interface method is introduced Now your colleagues must argue that the JLS of Java 8's wrong interface now contains classes that do not meet the purpose of the interface However, this is a feasible extreme position, but there is no result

You just need to avoid discussion by exporting your own interface from the library interface and providing a default empty implementation for all inherited methods

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

    ...
}

Or you can all view the following design, which seems suspicious to me, causing you to discuss the default method in the interface:

The solution may be to simply split many smaller interfaces

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>