Prefer composition over inheritance?

Question :

Prefer composition over inheritance?,

Answer :

Why prefer composition over inheritance? What trade-offs are there for each approach? When should you choose inheritance over composition?

,

Prefer composition over inheritance as it is more malleable / easy to modify later, but do not use a compose-always approach. With composition, it’s easy to change behavior on the fly with Dependency Injection / Setters. Inheritance is more rigid as most languages do not allow you to derive from more than one type. So the goose is more or less cooked once you derive from TypeA.

Read More  Broadcast like UDP with the reliability of TCP

My acid test for the above is:

  • Does TypeB want to expose the complete interface (all public methods no less) of TypeA such that TypeB can be used where TypeA is expected? Indicates Inheritance.
    • e.g. A Cessna biplane will expose the complete interface of an airplane, if not more. So that makes it fit to derive from Airplane.
  • Does TypeB want only some/part of the behavior exposed by TypeA? Indicates need for Composition.
    • e.g. A Bird may need only the fly behavior of an Airplane. In this case, it makes sense to extract it out as an interface / class / both and make it a member of both classes.
Read More  How to obtain good concurrent read performance from disk

Update: Just came back to my answer and it seems now that it is incomplete without a specific mention of Barbara Liskov’s as a test for ‘Should I be inheriting from this type?’

That’s the answer Prefer composition over inheritance?, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.

Disclaimer :

The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you

Read More  ILMerge Best Practices