Design Principals – Favour of composition over Inheritance

Posted 15 December 2020

Inheritance is main state of object oriented design and programming. with in inheritance we can avoid code duplication by inheriting behaviors. this is the powerful techniques but this technique that can easily be overused. it also a technique that can lead to design that far to rigged and not extensible. So

Identify the aspects of your application that vary and separate them from what stays the same . this call Favour of composition over inheritance


Here above example Coffee shop have coffee menu with different condiment

Adding simple super class for Coffee and extend for different Coffee with condiments. think what happen when customer wants tow more condiments or different topping or  glass of milk.We want o customize or override function every time or code duplicates so that’s not maintainable and extensible

Instead of a coffeeWithButter IS-A Coffee ? what about a coffee HAS-A Condiments ?

Here We can add our condiments through addCondiments function to add condiment and calculate cost. with this design we get the benefits of REUSE without all the baggage that comes along with inheritance

When you put two classes together like this you are using composition. Instead  of inheriting their behavior, the Coffee get their behavior by being composed with the right behavior object

As you have seen creating system using composition gives you lot more flexibility . Not only does it let you encapsulate a family of algorithms into their own set of classes, but it also change behavior change at runtime  as long as object you are composing with implements the correct behavior interface. composition is used in many design patterns


With Composition

  • We can add any number of condiment easily at runtime
  • Implementing new condiments by adding a new class
  • No code duplicates
  • Avoid class explosion


Favour of composition over Inheritance

  • Instead of inheriting behavior, we can compose our object with new behavior
  • Composition often gives is more flexibility, even allows behavior changes at runtime
  • Composition is a common techniques used in design pattern




Leave a Reply

Your email address will not be published. Required fields are marked *