Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java writing libraries

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

My library expects a lot of configuration for which I have created interfaces and default Impl classes, but now my library requires a lot of interaction with the calling outside. This is also done via interfaces, but I've got the feeling that the user is forced to override too many methods that just return some default fault or even null. Is there some nicer way to make all these "you can but you don't have to implement" parts more optional?

like image 226
user1282232 Avatar asked Mar 21 '12 01:03

user1282232


1 Answers

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

The abstract base class can provide default implementations of methods so that your library user doesn't need to create these themselves. It can also define abstract methods that the API user must implement if they want to create a concrete 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();
    }
}
like image 107
mikera Avatar answered Sep 21 '22 18:09

mikera