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

Verify, standardize, and correct the Big 4 + more– name, email, phone and global addresses – try our Data Quality APIs now at Melissa Developer Portal!

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.

Developers! Quickly and easily gain access to the tools and information you need! Explore, test and combine our data quality APIs at Melissa Developer Portal – home to tools that save time and boost revenue. 

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 }}