# composition over inheritance

# sources

The Two Pillars of JavaScript: Part 1: How to Escape the 7th Circle of Hell by Eric Elliott 20141021

Composition over Inheritance : Youtube channel Fun Fun Function

# explanation

inheritance is when you design objects around what they are

composition is when you design objects around what they do

# example

We design a game where we have

Dog
  .poop()
  .bark()

Cat
  .poop()
  .meow()
1
2
3
4
5
6
7

Because of poop function duplication we create a mother class

Animal
  .poop()

    Dog
      .poop()
      .bark()

    Cat
      .poop()
      .meow()
1
2
3
4
5
6
7
8
9
10

Now we add more classes on a different line of inheritance

MurderRobot
  .drive()
  .kill()

CleaningRobot
  .drive()
  .clean()

Animal
  .poop()

    Dog
      .poop()
      .bark()

    Cat
      .poop()
      .meow()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

Same problem as before, we need another mother class for robots

Robot
  .drive()

  MurderRobot
    .kill()

  CleaningRobot
    .drive()
    .clean()

Animal
  .poop()

    Dog
      .poop()
      .bark()

    Cat
      .poop()
      .meow()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

After a while a new needs is coming : We need a murder robot dog who can kill, drive and bark. But it cannot poop (no digestive system)

At this point, the class inheritance taxinomy is deeply wrong. We cannot put a MurderRobotDog class inside.

The only solution keeping inheritance is to set a super motherclass but children will have method they should not have in attached to them. So it is bad.

This problem is called the Gorilla Banana Problem (You request a Banana, you got a Gorilla and the entire Jungle with it).

The solution is composition (design objects around what they do)

dog            = pooper + barker
cat            = pooper + meower
cleaningRobot  = driver + cleaner
murderRobot    = driver + killer
murderRobotDog = driver + killer + barker
1
2
3
4
5

# when to use composition/inheritance

Lots of devs just favors composition over inheritance and some never use inheritance.

Replace Constructor with Factory Method : Martin Fowler 1999

He is not saying inheritance is bad directly but if you don't use constructors you cannot use super keyword.

CallSuper is an anti-pattern: Martin Fowler 20050811

or a code smell

Composition over inheritance : en.wikipedia.org

Composition vs. Inheritance: How to Choose? 20150512

# articles

The Open Minded Explorer’s Guide to Object Composition : Eric Elliott 20151015

Composition over Inheritance, the importance of context : Damien Lebreuilly 20160131

In the rest of this article, I’ll explain what are those inheritance pitfalls that composition (in GoF sense) tries to avoid, and I’ll show that concatenative inheritance still carries them.

he is taking the @mpj murderRobotDog example adding more complexity to output this conclusion : Object composition is not object merging.