Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Java Holiday Calendar 2016 (Day 2): Favor Composition Over Inheritance

DZone's Guide to

Java Holiday Calendar 2016 (Day 2): Favor Composition Over Inheritance

When you're working with your classes, make sure to use composition when you can for better separation of concerns, among a variety of other reasons. See how it's done.

· Java Zone ·
Free Resource

Learn how to build stream processing applications in Java-includes reference application. Brought to you in partnership with Hazelcast.

Image title

Today's tip 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 here on DZone, which goes into more about API Design with Java 8.

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

Learn how to build distributed stream processing applications in Java that elastically scale to meet demand- includes reference application.  Brought to you in partnership with Hazelcast.

Topics:
java ,inheritance ,composition ,separation of concerns

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}