Choosing Between Inheritance and Composition(Aggregation)

Please visit Inheritance vs Composition vs Aggregation before you read further into this particular blog.

There is a very famous design principle  which saysFavour Composition over Inheritance

Let’s us look into some of the reasons which led to the above statement:

  1. Composition allows to change behavior of a class at runtime by setting property during runtime and by using Interfaces to compose a class we use polymorphism which provides flexibility of to replace with better implementation any time.
  2. Composition offers better test-ability of a class than Inheritance. If one class is composed of another class, you can easily create Mock Object representing composed class for sake of testing. Inheritance doesn’t provide this luxury. In order to test derived class, you must need its super class. Since unit testing is one of the most important thing to consider during software development, especially in test driven development, composition wins over inheritance.
  3. In inheritance, a change in superclass might cause problems in derived class, that inherit it.If sub class is depending on super class behavior for its operation, it suddenly becomes fragile. When behavior of super class changes, functionality in sub class may get broken, without any change on its part. Composition provides more loose coupling between the concerned classes.
  4. One reason of favoring Composition over Inheritance in Java is fact that Java doesn’t support multiple inheritance. Since you can only extend one class in Java, but if you need multiple functionalities you should opt for Composition.

When to use Composition

Don’t use inheritance just to get code reuse If all you really want is to reuse code and there is no is-a relationship in sight, use composition.

Always check whether the IS-A relationship exists between the derived classes and the base class. If the IS-A relationship does not hold, it’s better to use composition instead of inheritance.

Leave a Reply

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