I keep hearing that composition should be preferred over inheritance. When does inheritance offer a real advantage in object-oriented design?
When is inheritance actually better than composition?
Answers
Inheritance can be a good fit when the domain has a stable hierarchy and the derived type really can be used wherever the base type is expected. The useful test isn't just whether you can say โis aโ. Check whether the subclass can honor the base class's behavioral expectations too.
If a subclass needs to reject normal base-class operations or change their meaning, the hierarchy may be fighting the design. Composition lets you assemble different capabilities without forcing those types into the same implementation hierarchy.
Reply to this answer
UI frameworks are a practical example. If a framework provides a button class with a lot of behavior you want to keep, subclassing it and overriding a few documented methods can be much simpler than rebuilding or forwarding all that behavior.
That works best when the framework is designed for extension. A deep hierarchy can become difficult to understand, especially when changes in a base class affect several layers of subclasses.
Reply to this answer
Separate interface inheritance from implementation inheritance. If all you need is to pass different objects to a function using the same contract, an interface can do that without sharing a base class implementation.
Inheritance of implementation becomes more compelling when there's useful shared behavior and a deliberate way for subclasses to customize part of it. A template method is one example: the base class defines the overall process and calls methods that subclasses can specialize.
Reply to this answer
There can also be a performance difference in how calls are dispatched. A virtual call may use one indirect dispatch, while a composed design might add forwarding calls. That depends on the language, compiler, and design though, so I wouldn't choose a hierarchy on that basis without measuring.
Reply to this answer
Add your answer
Answers are reviewed before publication.
p.358~ferrulewrench:
The same idea can apply to a dependency you can't change, provided it exposes suitable methods for overriding. It's worth checking whether the library actually supports that extension point.