Day 2, Java Holiday Calendar 2016, Composition

by Per Minborg

on December 2, 2016

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.

About

Per Minborg

Per Minborg is a Palo Alto based developer and architect, currently serving as CTO at Speedment, Inc. He is a regular speaker at various conferences e.g. JavaOne, DevNexus, Jdays, JUGs and Meetups. Per has 15+ US patent applications and invention disclosures. He is a JavaOne alumni and co-author of the publication “Modern Java”.