Object-Oriented Design – ‘Extends is Evil’ vs. OCP

design-principlesobject-oriented

As far as I have understood(?), the "Extends is evil" idea is in direct opposition to the Open Closed Principle?

In here, the concept of OCP is presented as inherently using Extends:
http://www.oodesign.com/open-close-principle.html

While in for example this article, the act of extending is considered a capital offense?
http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html?page=1

What is the correct way to satisfy both OCP and not using Extends? Consider a simple BulletinBoard class that has Posts, which can be either NewsPosts or GuestbookPosts with different properties, but same methods/behaviour.

Best Answer

No, it is not.

Open-closed principle calls for encapsulating functionality in the classes. It does not say whether the interface should be defined by base class or interface.

"extends is evil" tells you to prefer implementing interfaces over extending base classes.

Since open-closed principle is fine with either, they are not opposed.

As for the "extends is evil", there are several reasons for which inheritance is used and Java does not let you distinguish them (C++ has protected and private inheritance that helps here):

  1. Implementing common interface for other code to use.
  2. Reusing base functionality.
  3. Specializing behaviour of mostly generic class.

You should use interfaces for the first so you don't tie yourself into single inheritance hierarchy. That's the main message of "extends is evil".

For the second the preferred method is composition, again so you don't tie yourself to single inheritance hierarchy.

But for the thirds, extending (abstract) base class is appropriate. Your example falls in the third case.

Note however, that the abstract base class should probably still implement an interface and the code should use it whenever it does not need the particular base class, which is most of the time.

Note:

evil, adj.: Something you should avoid most of the time, but not something you should avoid all the time. For example, you will end up using these "evil" things whenever they are "the least evil of the evil alternatives." (C++ FAQ)

That applies in all similar cases where somebody calls some technique "evil". It does not mean you must not use it, ever. Just points out there is a preferred alternative.

Related Topic