Composition vs. Inheritance
I was thinking about composition vs. inheritance today and I wanted to make everything crystal clear. Here’s some quick brain-dump of my research and thoughts:
Use composition when possible. It delegates the dependency process to the callsite. This is a prefer composition over inheritance. Since modern programming idioms prefer composition to inheritance, most of the time using delegates and Dependency Injection to achieve composition would be a Good Thing.
Why prefer composition to inheritance? Simply because inheritance is almost the strongest coupling you can introduce between two classes (second to
friendclasses in C++). We all know that coupling is bad and that separation of concern is good.Use Inheritance whenever necessary. An example of a necessary case is when the new functionality (injection point) needs to access the protected members of the base class.
When using Inheritance, prefer nonpublic inheritance to public inheritance. Use private inheritance when you need to access the protected members of the base class; use protected inheritance when you need to access the protected members of the base class, while at the same time exposing them to your derivatives.
Only use public inheritance when your derived class is a true IS-A relationship that satisfies the Liskov Substitution Principle.
There is a good quote from somewhere:
Inherit (publicly) not to reuse, but to be reused.
Is there anything that inheritance can do but composition can’t do?
Yes, when you want to access protected members of the base class.
Theoretically, this could still be done using composition by having the base class pass along the required attributes, but that often quickly degenerates into passing a chain of message.
Even if you pass an instance of the Base class to the Derived class in hope of that the Derived class can access the Base class, it’s still limited to the public interface only.