Object-Oriented Design – Does Multiple Inheritance Violate Single Responsibility Principle?

multiple-inheritanceobject-orientedobject-oriented-designsingle-responsibility

If you have a class which inherits from two distinct classes, does not this mean that your subclass automatically does (at least) 2 things, one from each superclass?

I believe there is no difference if you have multiple interface inheritance.

To be clear, I believe that if subclassing multiple classes violates SRP, then implementing multiple (non-marker or basic interface (e.g. Comparable)) interfaces violates SRP too.

Best Answer

In a very narrow sense, the answer is "Yes": assuming that your base classes or interfaces are designed for a single purpose, inheriting both of them does create a class with multiple responsibilities. However, whether or not it is "a bad thing" depends on the nature of the classes or interfaces that you are inheriting.

You can partition your classes and interfaces into two major groups - the ones addressing the essential complexity of your system, and the ones addressing its accidental complexity. If you inherit from more than one "essential complexity" classes, it is bad; if you inherit from one "essential" and one or more "accidental" classes, it is OK.

For example, in a billing system you could have classes for representing invoices and billing cycles (they address the essential complexity) and classes for persisting objects (they address the accidental complexity). If you inherit like this

class BillingCycleInvoice : public BillingCycle, public Invoice {
};

it is bad: your BillingCycleInvoice has a mixed responsibility as it relates to the essential complexity of the system.

On the other hand, if you inherit like this

class PersistentInvoice : public Invoice, public PersistentObject {
};

your class is OK: technically, it services two concerns at once, but since only one of them is essential, you can write off inheriting the accidental one as the "cost of doing business".

Related Topic