The inheritance pattern was always like an assumption of the best, one and only solution of creating groups of concepts. In the workplace, on the university, in hobby projects, in books. Because if quad is a rectangle, then it’s afolso a figure. So it’s a perfect candidate for an inheritance design.
IS A, IS A, IS A
One of the guidelines taught on the university and in some books about c++:
- Q: ‘When should you use composition and when inheritance?’
- A: ‘When the relationship is more like ‘IT IS’, use inheritance. If the ‘IS COMPOSED FROM’ is more accurate, use composition.’
Whatever project I’ve seen, most of them had an impressive inheritance tree. Sometimes it seemed that multiple level of classes was just for the source code to look smart. In the advanced stage of the project, the whole designed structure was turning out to be flawed. In the result it was bent in an ugly way to fit the new requirements. Not to mention about the journey through all the ancestors to figure out how the youngest class is really behaving.
We have a BehaviorA, BehaviorB and BehaviorC. Then we have a concept, which should behave using A and B, and another concept which should behave using B and C. Inheritance says: make base class with A behavior. And then add two classes: one for B and one for C separately. Both of them should inherit from A. Think about it: what’s the point of that? What if another concept is introduced, which should have A, B, C, D behavior? Why not use a factory function which will know A, B, C, D and then just compose those behaviors into a needed concept? Ok, it’s not so sophisticated as inheritance. But isn’t that just simpler?
Inheritance locks groups of behaviors into permanent concepts. Shouldn’t those behaviors be freed and used as the building blocks?
BEHAVES LIKE, BEHAVES LIKE, BEHAVES LIKE
Recently I was relieved, that what intuitively seems to me as a winning solution was backed in this video:
“I don’t see the point of using the inheritance at all. I don’t think it’s a good pattern. I don’t think it should be used.“
Another article, this time from Eric Elliot: https://medium.com/@_ericelliott/what-you-were-taught-was-not-prototypal-inheritance-f853ce3db00e#.cgs1zt2di
“Favor composition over class inheritance” – the Gang of Four
‘Composition over inheritance’ and yet, the second one seems to reign in majority of the projects.