11 April 2015

prefer composition over inheritance

During design discussion have you heard about the phrase "prefer composition over inheritance" and wondered what does that mean? In this post let's see what actually means when your architect says "prefer composition over inheritance" .

Inheritance is one of the building blocks of OOPS. We have been taught to use inheritance in class designs. Using inheritance, you also gain code reuse. Code re-usability is definitely a good coding practice. Then what's the phrase "prefer composition over inheritance" and what's wrong with inheritance?

Actually there is nothing wrong with inheritance. Inheritance should be used to define a hierarchical relationship. If you don't see a hierarchical relationship between two entities, then don't use inheritance just to gain code re-usability. Your motive to use inheritance shouldn't just code re-usability.

An example showing use of composition over inheritance

Let's consider Televisions. Television shows running pictures, produces sound and gets various channels. In real-world Television make use of display screens to show pictures, speakers to produce sound and set-top box to get channels. So Television should have all these functions.

There are two options for Television to exhibit its capabilities:

  • OPTION #1: Television class can derive from Screen display, Speakers and set of box, etc to get their capability.
  • OPTION #2: Instead compose Television class to get required functionality.
class diagram showing prefer compoistion over inheritance

Disadvantage of using inheritance to build Television class

Inheritance is a IS A relationship. In real-world Television set IS not just a speaker. Saying Television IS A screen display doesn't make much sense. Television is much more than above-said capabilities. So making Television class to derive from individual specialized classes doesn't establish a proper IS A relationship.

Advantage of preferring object composition over inheritance to build Television

Composition represents HAS A relationship. Applying this to television it makes sense to say, Television HAS A screen display, Television HAS A speaker and HAS A set of box. Here COMPOSITION represents the relationship better between the Television and the individual devices it makes use of. And hence the saying "PREFER COMPOSITION OVER INHERITANCE".

Having said "prefer composition over inheritance", inheritance isn't going away. Inheritance is definitely one of building block of OOPS, it has its use cases to represent real-world hierarchical relationship; for more info refer Inheritance in OOPS.

You might be interested in the below blog posts.

Loose coupling v/s tight coupling

Singleton design pattern explained with an example

Implementin IComparer for multiple types sorting of requirements

No comments:

Post a Comment