
Why composition is often better than inheritance - exch
http://joostdevblog.blogspot.com/2014/07/why-composition-is-often-better-than.html
======
al2o3cr
Meh. I think this phrase has been repeated until it has lost any connection
with the original intent and turned into a generic "INHERITANCE BAD!
COMPOSITION GOOD!" without much meaning attached to either word.

I haven't found the original source, but I've always presumed the statement
originally referred to some of the bizarro "inheritance-as-composition" stuff
in the early C++ days: for instance, you might have a class 'Window' and a
class 'Button', then combine them with multiple inheritance to get a
'WindowWithButton', then inherit from _that_ and a 'Scrollbar' class to get
'WindowWithButtonAndScrollbar'.

I can't imagine anybody thinking of that as a "good" pattern today, but
remember it was the '90s. :)

Nowadays, the basic statement has been dogmatized to the point where you get
code like this:

[https://github.com/elm-city-
craftworks/broken_record/blob/ma...](https://github.com/elm-city-
craftworks/broken_record/blob/master/lib/broken_record/composable.rb)

This code re-implements Ruby's built-in method lookup algorithm, but with per-
instance objects and none of the optimizations available to the real thing. It
basically remakes inheritance, slowly and poorly, using composition.

The other one that makes me scratch my head: people who rail against
inheritance, then suggest mixins as an alternative. At least in Ruby, the two
are _equivalent_. Check the `ancestors` property on a class with mixins
sometime if you don't believe me.

TL;DR (too late) - use your damn brain to make decisions, not just parrot
slogans.

~~~
joevandyk
You can only inherit from one class in ruby. You can mixin multiple modules
into a class. So they aren't entirely equivalent.

~~~
stouset
Under the hood, mixing in modules _actually is_ inheritance. An anonymous
class is created that has all the module's methods, and this class is added to
the inheritance hierarchy.

They are quite literally identical, even if Ruby tries it's best to hide that
fact.

------
userbinator
While it's possible to overuse inheritance, I don't think replacing it with
composition is all that much better, and in addition all those forwarding
methods that do nothing more than call another (could they even be optimised
out?) are a great example of code that would need to be written, consuming
resources like programmer time, but otherwise serves no true useful purpose to
the functionality of the software. The complexity only changes form, so
instead of tracing the flow through an inheritance hierarchy you're just doing
it through chains of forwarding methods. It's for this same reason I don't
believe so much his argument for readability and short classes - breaking
everything up does not make things simpler, it makes the complexity spread out
over a larger area; while it may be true that it is easier to understand an
individual piece, it becomes more difficult to understand the system as a
whole. This is especially important when debugging, where "can't see the
forest for the trees" is a big hindrance.

I think his example of flexibility is the strongest argument for composition,
because in that case the forwarding methods are not a waste - they would need
to do (useful) work to determine which of the multiple composited objects they
would need to work with.

Being mostly a C programmer who does OO-things, I use inheritance when it's
obvious that most of the "methods" will be passthroughs to the "superclass",
and composition when there is something more that needs to be done. Also, as I
am not constrained by the OO model/conventions of the language, it's more
flexible in that I can do things like "inherit" multiple times and even change
that at runtime, so there is really no strict separation between composition
and inheritance; to me, it's just "which function do I set this to point to."

~~~
twic
> The complexity only changes form, so instead of tracing the flow through an
> inheritance hierarchy you're just doing it through chains of forwarding
> methods. It's for this same reason I don't believe so much his argument for
> readability and short classes - breaking everything up does not make things
> simpler, it makes the complexity spread out over a larger area; while it may
> be true that it is easier to understand an individual piece, it becomes more
> difficult to understand the system as a whole.

Preach it! Whilst immense monolithic classes are bad, smashing a system up
into a million tiny bits is just as much of a barrier to understanding. It is
baffling to me that this is not immediately obvious to everyone.

See also the microservices movement!

------
chton
While it's a well-written article, it really seems like beating a dead horse.
Composition over inheritance is a basic rule of OO programming, so much so
that it has its own wikipedia page
([http://en.wikipedia.org/wiki/Composition_over_inheritance](http://en.wikipedia.org/wiki/Composition_over_inheritance))

~~~
Torn
This horse still needs to be beaten.

Messy inheritance still plagues product Java, C#, and, with the increasing
proliferation of MVC frameworks, JS these days.

Hierarchies usually start out small. But, when new features are added and
scope creeps, they get deeper and more abstract and messier.

Substitutability (i.e. the L in SOLID principles) does require more boiler-
plate when using composition though. Interfaces and mixins (if available in
your language) go some way to helping.

~~~
tonyedgecombe
I wish we could move beyond this idea that just because someone uses a
particular language their code is going to be poorly written.

~~~
mamcx
But is true that some languages make some kind of bad/problematic code MORE
common, and requiere discipline and/or knowledge to combat it (and like in
this case, is likely that the avg developer is not aware of the alternatives
at all.)

------
kissgyorgy
In Python, we use mixins. Mixins can _only_ inherit from 'object' and nothing
else, like this:

    
    
        class PhysicsobjectMixin(object):
            def update_physics(self):
                pass
            
            def apply_konckback(self, force):
                pass
    
            def get_position(self):
                pass
    
    
        class FightMixin(object):
            def attack(self):
                pass
    
            def defend(self):
                pass
    
        
        class TalkMixin(object):
            def say_something(self):
                pass
    
    
        class Character(PhysicsobjectMixin, FightMixin, TalkMixin):
            pass
    
    
        class Pickup(PhysicsobjectMixin):
            pass
    
    
        class Projectile(PhysicsobjectMixin):
            pass
    
    

it's still inheritance, but the classes will be flat; every class only
inherits one deep, so there will be no diamond problems and no repeating code.

~~~
jhasse
I don't see the difference to interfaces.

~~~
Walkman
With interfaces, the above example would look like this:

    
    
        from abc import ABCMeta   
    
        class PhysicsobjectMixin(ABCMeta):
            @abstractmethod
            def update_physics(self):
                pass
            
            @abstractmethod
            def apply_konckback(self, force):
                pass
    
            @abstractmethod
            def get_position(self):
                pass
    
    
        class FightMixin(ABCMeta):
            @abstractmethod
            def attack(self):
                pass
    
            @abstractmethod
            def defend(self):
                pass
    
        
        class TalkMixin(ABCMeta):
            @abstractmethod
            def say_something(self):
                pass
    
    
        class Character(PhysicsobjectMixin, FightMixin, TalkMixin):
            def update_physics(self):
                pass
    
            def apply_konckback(self, force):
                pass
    
            def get_position(self):
                pass
    
            def attack(self):
                pass
    
            def defend(self):
                pass
    
            def say_something(self):
                pass
    
    
        class Pickup(PhysicsobjectMixin):
            def update_physics(self):
                pass
            
            def apply_konckback(self, force):
                pass
    
            def get_position(self):
                pass
    
    
        class Projectile(PhysicsobjectMixin):
            def update_physics(self):
                pass
            
            def apply_konckback(self, force):
                pass
    
            def get_position(self):
                pass
    
    

This is not DRY at all. I like mixins much better.

~~~
falcolas
It's not DRY, but then again, the chances of not overwriting, or more likely
adding something to that method are pretty small when your project becomes
more than an illustration of a principle.

For example, what if you want to add custom animations any time your
`Character` takes an action? Suddenly, all that boilerplate you "abstracted"
away through mix-ins is back, with a vengeance. How about if your physics for
a `Projectile` are different than for a `Pickup`? What if your character
suddenly picks up a Sling of Thrown Voices, and needs to apply conversation
snippets to its projectiles?

In simple examples, mixins are great and reduce a lot of boilerplate, but in
reality they are rarely so clean.

~~~
Walkman
> For example, what if you want to add custom animations any time your
> `Character` takes an action?

What's wrong with this?

    
    
        class Character(PhysicsobjectMixin, FightMixin, TalkMixin):
            def attack(self):
                # custom attack animation here
                return super(Character, self).attack()
    
            def defend(self):
                # custom defend animation here
                return super(Character, self).defend()
    

For me, it's still clear that 'attack' and 'defend' extends the funcionality
of the 'FightMixin'. I can see even the first glance, those are inherited
methods, because they use super() (call parent methods)

> How about if your physics for a `Projectile` are different than for a
> `Pickup`?

You need to implement two classes anyway. I see two possibilities:

I. If you have to implement this kind of different physics behavior only for
Projectile. (Maybe you don't even need a mixin.)

    
    
        class Projectile(object):
            def update_physics(self):
                pass
            
            def apply_konckback(self, force):
                pass
    
            def get_position(self):
                pass
    
    

II. If you have more Projectile-like objects, but they are not all the same.

    
    
       class FastMovingPhysicsobjectMixin(object):
            def update_physics(self):
                pass
            
            def apply_konckback(self, force):
                pass
    
            def get_position(self):
                pass
    
    
        class Projectile(FastMovingPhysicsobjectMixin):
            pass
    
        
        class Arrow(FastMovingPhysicsobjectMixin):
            pass
    
    

> What if your character suddenly picks up a Sling of Thrown Voices, and needs
> to apply conversation snippets to its projectiles?

Is this a weapon which doesn't shoot projectiles, but make damage with voice
or what? :D Then I think it's totally different, because if Character can have
all kinds of different weapons and those behave different ways, mixins don't
fit here. I would rather implement that like this:

    
    
        class Sword(object):
            def attack(self):
                # swing
    
            def defend(self):
                # defend
    
        
        class SlingOfThrownVoices(object):
            def attack(self):
                # shout loudly
    
            def defend(self):
                # pssszt, be quiet
        
    
        class Character(PhysicsobjectMixin, TalkMixin):
            def __init__(self, weapon):
                self.weapon = weapon
    
            def attack(self):
                # custom attack animation here
                self.weapon.attack()
    
            def defend(self):
                # custom defend animation here
                self.weapon.defend()
    

then weapon can be instance of either Sword or SlingOfThrownVoices. Note that
Mixins are still in use and no complicated inheritance problem occured even if
you have hundreds of weapons.

------
millstone
Consider how these things get stored. In the inheritance model, you might have
a big quad tree or some other data structure of PhysicsObjects, and just run
through and call updatePhysics() on all of them.

In the composition model, we now have multiple classes (Character, Pickup,
Projectile), each with an _unrelated_ updatePhysics(). This means code
duplication to call the relevant method on each separate class.

We could relate them all via an interface, instead of inheritance; now we can
store IEntity or whatever. We will soon discover three needs that are awkward
to address:

1\. Whenever we want to add some new method (say `fall`), we must go back and
implement it separately in each class.

2\. Different classes will want to share implementations. For example, both
Characters and Pickups bounce on fall.

3\. Some classes will want to specialize an implementation to do more.
Characters bounce on fall, but also take damage.

In practice you may end up with both: an interface that your engine talks to,
but also a common base class that provides sane defaults.

So while interfaces allow uniform interactions with disparate classes,
inheritance provides that and also the ability to share and specialize the
implementations. So inheritance solves some problems that interfaces cannot.

See also default methods in Java, which makes an interface more like a class,
and implementing an interface more like inheritance. The documentation even
says that a class that implements an interface inherits its default methods.

~~~
ufmace
I've seen this problem in projects I've worked on recently. It's gotten me
more interested in Ruby mixins as a solution, though I haven't worked on any
really complex object structures in Ruby. The project in question is in C#,
and you can sorta-almost do something like it by creating interfaces and
putting the methods that should be shared as extension methods on it, but it
feels very hacky.

------
jiaweihli
I think this is a tooling issue. People initially tend to favor inheritance
because it looks cleaner than composition. Mixing a lot of unrelated code in
the same class makes things hard to find. (which method applies to which
composed object?)

In languages that build in a concept of traits/mixins however, this isn't an
issue.

~~~
k__
I think so too.

In JS it's rather easy to compose objects. In Java it feels clunky, you code
looks kinda wrong when you done.

~~~
zo1
I don't quite understand this. In my opinion JS "classes", if you want to call
them that, look, feel and act very clunky. My opinion, of course... Please
could you explain to me how _you_ feel Java "classes" feel clunky and look
wrong? I'm genuinely curious, and open to being convinced.

 _Note_ I substituted your usage of "objects" with classes, because they're
vastly different concepts. I know, murky water when it comes to JS, but still.

~~~
k__
My point was, classes and inheritance feel natural in Java. Object-Composition
feels natural in JS.

------
taeric
I would prefer this with "why a shallower abstraction pool is better than a
deep one." I've seen some compositional concoctions that were just as terrible
to deal with as inheritance based ones. I think I've even
contributed/originated some.

------
zak_mc_kracken
We've known this since at least 1994, when the GoF book [1] famously said:

"Favor object composition over class inheritance"

[1] [http://www.amazon.com/Design-Patterns-Elements-Reusable-
Obje...](http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-
Oriented/dp/0201633612)

~~~
drumdance
Ha, that's one of the few things I remember from that book. (Not knocking the
book, just my poor memory.) I remember it being a big "a ha!" for a project I
was working on.

------
pllbnk
When I try to choose between the two, I often like to think if the object I
try to inherit from is from the same domain/context and solves a related
problem. In the example in the article a PhysicsObject solves the problem of
calculating coordinates in space and from the beginning it was not designed as
something to be used in the game by itself. While the character participates
in the actual game and executes the game logic. The character does not
'inherit' from PhysicsObject, it merely knows that PhysicsObject represents it
in the space.

------
teamhappy
It's pretty much the same example I used here a couple of days ago:
[https://news.ycombinator.com/item?id=7976227](https://news.ycombinator.com/item?id=7976227)

Game development seems to be the poster child for composition over
inheritance.

Here's a lengthy article that explains it way better (IMHO):
[http://gameprogrammingpatterns.com/component.html](http://gameprogrammingpatterns.com/component.html)

------
kilemensi
I think one of the biggest reasons why most libraries/frameworks/apps/etc. use
inheritance over composition is the easy with which the underlying languages
allow the use of inheritance as opposed to composition. Most of these software
writers know SOLID and other OO principles but when they're faced with the
actual implementation, inheritance is just too damned easy to implement.

------
andybak
The Wikipedia article chton mentions
([https://en.wikipedia.org/wiki/Composition_over_inheritance](https://en.wikipedia.org/wiki/Composition_over_inheritance))
ends with the following when discussing the drawback of composition
(boilerplate for forwarding methods): "This drawback can be avoided by using
traits or mixins."

Now this is where things get a little blurry for me.

Mixins can help with the main drawback of Composition - but Mixins ARE
inheritance - so isn't this a contradiction?

If I use PhysicsObjectMixin in my CharacterComposition class then I have to
inherit from it. So aren't we back with the perils of inheritance?

~~~
chton
the idea is that you create a mixin that has only the reference to the physics
object and the forwarding methods. If you implement that mixin, it will be
exactly equivalent as writing them out in your class, but you are spared from
having to do it for every single class with a physics object.

Remember that a mixin, by definition, isn't the same as inheritance. The
methods, fields and properties are compiled into the class, not inherited.
It's essentially a fancy way to 'include' a code file.

~~~
seanmcdirmid
Mixins can be implemented in a variety of ways, they don't need to be
unmodularly inlined into class/object definitions as in scala. Also, mixin-
style inheritance is by definition linearized multiple inheritance (at least
according to cook/bracha, things get weirder with the Gabriel/Common Lisp
definition).

~~~
chton
It's true that they can be implemented in the same way, but the idea remains
the same. Seeing mixins as inheritance is a far narrower definition than held
by most languages (or libraries) that implement them. Mixins don't put any
requirements on the polymorphism of the object that implements them, which
ordinary inheritance does.

It's common to use the Flavors/Lisp defintion of mixins, but I'll make sure to
read up on the Bracha-Cook paper about them.

~~~
seanmcdirmid
There have been many implementations of mixins, and many that I'm aware of,
like Scala, are inheritance based. The nice thing about mixin style
inheritance is that inheritance becomes much more composable. The type of an
object then is not its class, but the set of mixins it extends.

~~~
chton
Scala's implementation is definitely an interesting and a valuable one. I'm
not debating that inheritance-based mixins are useful, they definitely are.
It's just that they aren't necessarily inheritance-based, and there are many
implementations of mixins that aren't, so defining it as such is at best
somewhat limited and at worst misleading.

On a side note: scala's implementation, internally, is composition-based,
since they compile forwarding methods to static methods into the class. They
add an interface for those forwarding methods, so it can be used for
polymorphism (which is what allows the fun things) but for their system to
qualify as mixins, that interface is not necessary. For a very quick reference
about this, you can look at [http://stackoverflow.com/questions/2557303/how-
are-scala-tra...](http://stackoverflow.com/questions/2557303/how-are-scala-
traits-compiled-into-java-bytecode)

~~~
seanmcdirmid
The type enhancement means that traits could replace classes completely in
scala, which is kind of exciting. The problem with traits is that state must
be inlined even if implementations are not (so they are a mixture of mixins
and small talk style traits). I'm well versed in how they are implemented in
scalac.

What non-CL mixins are not inheritance based? Python?

~~~
chton
Oh absolutely, the type enhancement is what makes it so interesting to use,
but the point is that it's not necessary for it to be a mixin. It's a very
nice extra.

I'm not sure about python, but Ruby completely inlines the mixin's code. It
needs to do this because instance variables can be created anywhere, including
from inside the mixin, but they still need to apply to the object of the
actual class. This gives interesting cases for collisions, where 2 mixins
create the same instance variable, but it's a decidedly non-inheritance way of
doing it.

~~~
seanmcdirmid
I use a mixin pattern extensively in C# that involves an interface to say the
object provides a mixin object (C# also provides for partial classes, but its
not good enough). Polymorphism is preserved via this method (though all
clients delegate through MixX). Actually, I don't see private mixins (that
don't at least effect the object's v-table) to be very interesting: why not
just create and delegate to an object then?

------
kstenerud
In this case I'd argue that the roles are a bit messy and Character has too
much knowledge. Character should not know that physics objects can be updated,
and certainly shouldn't be calling updatePhysics. You could end up with an
updated Character interacting with a Character whose physics state hasn't been
updated yet.

applyKnockback: Character -> Physics object -> Physics engine

updatePhysics: Physics engine -> Physics object -> Character new position (x,
y)

updateCharacter: Character reacts to change

------
yayitswei
By the way, I encourage everyone to try out their game, Awesomenauts. Think
Super Smash Brothers meets Dota. It's a lot of fun to play!

------
javinpaul
Couldn't agree more than this. I have also shared my 2 cents on Why
composition is better than Inheritance for Java Programmers here
[http://javarevisited.blogspot.sg/2013/06/why-favor-
compositi...](http://javarevisited.blogspot.sg/2013/06/why-favor-composition-
over-inheritance-java-oops-design.html)

------
_pmf_
The burden of proof should fall onto the user of inheritance to justify his
decision. Interfaces plug delegates is more tedious to implement, but greatly
reduces the chances of an architecture turning into a complete train wreck.

I often wonder why declarative delagating is not a first class concern in
programming languages.

------
yeureka
In my opinion the best arguments against inheritance were written by Richard
Gabriel in his book Patterns of Software:
[http://dreamsongs.net/Files/PatternsOfSoftware.pdf](http://dreamsongs.net/Files/PatternsOfSoftware.pdf)

------
known
Sounds like
[https://en.m.wikipedia.org/wiki/Triarchy_%28theory%29](https://en.m.wikipedia.org/wiki/Triarchy_%28theory%29)

------
fithisux
Why often and not always? Can you provide an exceptional case?

~~~
arunix
Exception hierarchies?

~~~
fithisux
Thank you very much. I will do my homework.

