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

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

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.

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.

Topics:
java ,inheritance ,composition ,separation of concerns

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}