Composition over Inheritance
codingAdopt
Whenever it is possible, I prefer composition over inheritance. My arguments are:
- Liskov Substitution Principle. The L in SOLID states that "Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program.", the subclass should at least extend the functionality of the superclass instead of limiting it.
- Coupling. I have had to deal with with classes that inherited from other classes just to reuse part of the superclass, creating all kinds of problems and side effects when trying to refactor either class.
- Testing. I find it to be much easier to test behaviour through composition than through inheritance.
Obviously, there are cases when inheritance would be better over composition, most if not all these cases have to do with polymorphism. But in my experience, the big majority of the cases, composition would of have been a better solution.