Minborg

Minborg
Minborg

Thursday, December 1, 2016

Day 2, Java Holiday Calendar 2016, Composition

2. Favor Composition Over Inheritance



Today's tips is to avoid inheritance. For good reasons, there can only be one super class for any given Java class. Furthermore, exposing abstract or base classes in your API that are supposed to be inherited by client code is a very big and problematic API commitment. Avoid API inheritance altogether, and instead consider providing static interface methods that take one or several lambda parameters and apply those given lambdas to a default internal API implementation class.

This also creates a much clearer separation of concerns. For example, instead of inheriting from a public API class AbstractReader and overriding abstract void handleError(IOException ioe), it is better to expose a static method or a builder in the Reader interface that takes a Consumer<IOException> and applies it to an internal generic ReaderImpl.

Do This:

Reader reader = Reader.builder()
    .withErrorHandler(IOException::printStackTrace)
    .build();

Don't Do This:

Reader reader = new AbstractReader() {

    @Override
    public void handleError(IOException ioe) {
        ioe.printStackTrace();
    }
};

Read more in the original article at https://dzone.com/articles/the-java-8-api-design-principles

Follow the Java Holiday Calendar 2016 with small tips and tricks all the way through the winter holiday season.

No comments:

Post a Comment