Skip to content

Favour composition over inheritance

Devrath edited this page Feb 25, 2024 · 5 revisions

test

About Inheritance to watch out for

  • Inheritance is a powerful tool for code reuse but if used inappropriately, It could lead to building fragile software.
  • So inheritance is not bad in general.
  • Hey but say the hierarchy is a problem only when the class inheritance

Instead what to do as solution

  • Instead of existing a class, Provide a private field that references the class that we were supposed to inherit. and use --> Composition

So when to use inheritance anyway

  • It is a good choice to use inheritance when the new class ---> is a --> sub-class of the parent-class.
  • Basically when the new class is a subtype of the parent.
  • Inheritance should be used for meaningful type hierarchy and not just code reuse.

What does it mean by a sub-class to be a sub-type and when it's not a sub-type

  • The principle that deals with subtypes is Liskov substitution Principle.
  • A class can be a sub-type if a class satisfies the Liskov substitution Principle.
  • There has to be Is-a relationship between parent and child.

Inheriting the flaws 🤔

  • Be sure when you are inheriting the class, The flaws are also inherited.
  • Instead you can use composition that lets you hide these flaws.
  • Ex:-> Usage of context in the android, See its usage everywhere given if it's not needed. So they forced the usage of context to all the android developers in the world which is a bad design.