Java Letter Libraries

I'm trying to write my first library, but I still run into some design issues.

My library expects a lot of configuration, for which I created Impl default interfaces and classes, but now my library needs a lot of interaction with an external call. This is also done via interfaces, but I feel that the user is forced to override too many methods that return only a default error or even null . Is there any more convenient way to make all of these “you can, but cannot realize” parts more optional?

+7
source share
2 answers

Even if you are creating an interface, it often also makes sense to create an abstract base class that your library users can extend to implement the interface.

An abstract base class can provide standard method implementations so that the library user does not need to create them. It can also define abstract methods that an API user must implement if they want to create a specific subclass.

 public abstract class MyBaseClass implements MyInterface { // abstract method // anyone who extends must implement this public abstract void myMethod1(); // default error implementation // overriding is optional, but if used it will throw an error public void myMethod2() { throw new UnsupportedOperationException(); } // default implementation that subclasses may find useful: public void doBothMethods() { myMethod1(); myMethod2(); } } 
+10
source

This is certainly an area where there was no perfect approach. It was recognized as such and was examined using public defender methods. The link will lead you to the official language extension proposal.

Therefore, I would recommend that you stick with the interfaces and provide standard implementations of each method using static library methods. Thus, you are ready when the method of a bona fide defender becomes available.

+2
source

All Articles