DEV Community

Discussion on: When isn't inheritance used?

Collapse
 
rhymes profile image
rhymes

Composition is almost always the better choice. It favors reusability and you can inject dependencies which also makes testing easier. I guess it's also easier to move things around with it.

Another pro of composition is that inheritance (especially multiple inheritance) makes it hard to track down dependencies and sometimes introduces ordering problems (if you inherit from X and Y and both inherit from A then you're inheriting from A twice in theory).

Inheritance tightly couples implementation details between the sub and superclass, whereas composition favors using just the interface.

I'd say inheritance is okay if there's an is a relationship and if your inheritance tree is really shallow (I wouldn't go past 1 in your own code TBH :D).

Another shortcoming of inheritance is that with composition it's easier to change implementation at runtime.