The Problem of Implementation Inheritance

Courtesy:  Allen Holub

Why extends is evil
Improve your code by replacing concrete base classes with interfaces

The extends keyword is evil; maybe not at the Charles Manson level, but bad enough that it should be shunned whenever possible. The Gang of Four Design Patterns book discusses at length replacing implementation inheritance (extends) with interface inheritance (implements).

Good designers write most of their code in terms of interfaces, not concrete base classes. This article describes why designers have such odd habits, and also introduces a few interface-based programming basics.

Interfaces versus classes

I once attended a Java user group meeting where James Gosling (Java’s inventor) was the featured speaker. During the memorable Q&A session, someone asked him: “If you could do Java over again, what would you change?” “I’d leave out classes,” he replied. After the laughter died down, he explained that the real problem wasn’t classes per se, but rather implementation inheritance (the extends relationship). Interface inheritance (the implements relationship) is preferable. You should avoid implementation inheritance whenever possible.

Losing flexibility

Why should you avoid implementation inheritance? The first problem is that explicit use of concrete class names locks you into specific implementations, making down-the-line changes unnecessarily difficult.

From JavaScript perspective, you don’t need classes. Why?

Peter Michaux explains:

The goal of Java’s extends, and inheritance in general, is code reuse (function reuse mainly.) We don’t want to retype code we already typed once and we really don’t want to maintain multiple copies of the same code. So code reuse is our main goal. It turns out that JavaScript is better equipped to reuse functions then most languages because JavaScript functions are first-class objects. You can grab a function-valued property from one object and attach it as a property of another object. If you grab all the properties of one object and attach them to another object you have, in essence, mixin-style multiple inheritance.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s