5

Possible Duplicate:
Where does this concept of “favor composition over inheritance” come from?

I have colleagues at work who claim that "Inheritance is an anti-pattern" and want to use composition systematically instead, except in (rare, according to them) cases where inheritance is really the best way to go.

I want to suggest an alternative where we continue using inheritance, but it is strictly forbidden (enforced by code reviews) to use anything but public members of base classes in derived classes.

For a case where we don't need to swap components of a class at runtime (static inheritance), would that be equivalent enough to composition? Or am I forgetting some other important aspect of composition?

marked as duplicate by pdr, Steven Jeuris, Walter, Caleb, Eric King Nov 12 '12 at 19:48

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

11

You're sort of looking at it backwards. Composition isn't preferred because of some unseen benefit of composition, it's preferred because it avoids the drawbacks of inheritance. Inheritance adds the significant benefit of substitutability. However, that benefit comes with the significant cost of tight coupling. Inheritance is the strongest coupling relationship possible. If you don't need the substitutability, the coupling cost isn't worth it.

Your restricted version of inheritance addresses its other cost, a loss of encapsulation, but does nothing about the much more significant cost of coupling.

  • 2
    Thanks Karl, that's the kind of thing I was looking for. – Frank Nov 12 '12 at 18:38
  • 1
    This may be the best explanation of this concept I've ever seen. – Magus May 13 '14 at 16:12
4

I think the difference between the two things is in their intent. Is the class you are writing really meant to be used as replacement / specialisation of its Base class or is it just using some functionality? If the First Case is true you should go with inheritance. If the latter is true go for composition. In my experience using inheritance where composition would be appropriate creates a more complex, less understandable and meanigful codebase.

Not the answer you're looking for? Browse other questions tagged or ask your own question.