-
Notifications
You must be signed in to change notification settings - Fork 0
Favour composition over inheritance
Devrath edited this page Feb 25, 2024
·
5 revisions
- 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 of existing a class, Provide a private field that references the class that we were supposed to inherit. and use -->
Composition
- It is a good choice to use inheritance when the
new class
--->is a
-->sub-class
of theparent-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.
- 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.
- 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.
.