Question

This post is based on the question https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance/11758048#comment15634305_11758048.

Some people said - check whether there is “is-a” relationship. If it is there use inheritance. What I think is there should be a second check for using inheritance. Use inheritance only if the base class is abstract. If the base class need to be instantiated then use composition; not inheritance.

E.g 1. Accountant is an Employee. But I will not use inheritance because a Employee object can be instantiated. (When you talk to business people, they will tell you - Accountant is an Employee. But in OO world Accountant is not (should not be) an employee)

E.g 2. Book is a SellingItem. A SellingItem cannot be instantiated - it is abstract concept. Hence I will use inheritance. The SellingItem is an abstract base class (or interface in C#)

What I am looking for here is an example that will challenge my argument –that is a scenario in which inheritance is better than composition even though the base class is non-abstract (base class can be instantiated). Can you please provide such an example?

Note: It would be more helpful if you can provide a scenario based on Bank domain, HR domain, Retail domain or any other popular domain.

Note: In the design, please assume that we have full control of the code. That is we are not using any external API. Also we are starting from beginning.

I will mark as answered if there is an example that explains a scenario that proves my argument is wrong. It is not a mere discussion on whether to use Composition or Inheritance.

I support @anon answer in https://stackoverflow.com/questions/3351666/why-use-inheritance-at-all?lq=1

The main reason for using inheritance is not as a form of composition - it is so you can get polymorphic behaviour. If you don't need polymorphism, you probably should not be using inheritance.

@MatthieuM. says in Code Smell: Inheritance Abuse

The issue with inheritance is that it can be used for two orthogonal purposes:

interface (for polymorphism)

implementation (for code reuse)

REFERENCE

  1. Employee- Accountant Example https://stackoverflow.com/questions/11759120/issue-in-using-composition-for-is-a-relationship
  2. Selling Item Example - https://codereview.stackexchange.com/questions/14077/is-it-proper-tpt-inheritance
  3. Programming SOLID Principles
  4. Code Smell: Inheritance Abuse

No correct solution

Licensed under: CC-BY-SA with attribution
scroll top