I know this as a rule of thumb for a long time now but I still don’t know the actual reason behind it. An easy to understand explanation will be deeply appreciated.
@ron_man This is something I'm trying to learn more about as well. I've been exploring the Elm language, which is a purely functional object-oriented language and it has opened my eyes to some of the benefits. Essentially as I understand it, if your objects/functions are composable they are not reliant on one another.
However if your object extends another, it is now reliant on that previous objects API -- class A extends class B. Do this a couple more times and you've got class D extends class C (which extends class B, which extends class A. What if I make a change to class A? It starts to get hard to figure out if that's going to break the other 3 classes.
With composition I can say class D is composed of class A, class B, class C. It doesn't inherit from any of them, it is composed of each of their unique structures.
I hope this is a good explanation - I'm sure it's one that could use some help/fixing as my understanding of this concept is still growing as well.
Jon LeMaitre
full stack web dev
I'll use a simple example that you might encounter in a game:
class Weaponandclass Tool. Weapons are used for attacking enemies, and have properties like damage, range etc. Tools are used for exploring the world: prying open lockers, breaking down doors. They have properties like weight, lifespan, etc.So what should a
Crowbarextend from if the game rules say it can be used as both a weapon, and a tool? To add even more complexity, what happens when you haveclass RangedWeapon extends Weaponandclass MeleeWeapon extends Weapon? The crowbar is both. You can throw it, or beat people with it. So even if you decided it should extend fromWeapon, which sub-class of weapon should it extend from?Instead, it would be better if you could combine different behaviors together. Combine
RangedAttack,MeleeAttack,Leverage, andSmashbehaviors together into a new game element calledCrowbar. There is no inheritance tree or taxonomy to worry about - only discrete behaviors which can be combined in different ways to form new weapons/tools/gameplay elements.