r/node • • Sep 21 '15

Composition over Inheritance

https://medium.com/humans-create-software/composition-over-inheritance-cb6f88070205
17 Upvotes

6 comments sorted by

3

u/dukerutledge Sep 21 '15 edited Sep 22 '15

This is why type classes and protocols are the bomb. They give us the added bonus of speaking about a shared interface, but not needing the exact same behavior. We can share behavior when needed, but tweak behavior for specific use cases. I'm looking forward to efficient type classes/protocols with the introduction of Symbols:

const symWalk = Symbol("walk");

// The interface
const walk = (x) => x[symWalk](x);

// Creating the interface
walk.derive = (x, behavior) => {
  x.prototype[symWalk] = behavior;
};

// Reflection to retrieve the behavior
walk.instance = (x) => x.prototype[symWalk];

const Dog = function (name) {
   this.name = name;
};
walk.derive(Dog, x => {
   console.log("bounce bounce, I'm " + x.name);
});

const Robot = function (name) {
   this.name = name;
};
// Different behavior same interface
walk.derive(Robot, x => {
  console.log("grind grind my gears, I'm " + x.name)
});

const Cat = function (name) {
   this.name = name;
};
// Reusing an instance
walk.derive(Cat, walk.instance(Dog));

walk(new Dog("Fido"));
walk(new Robot("Dot"));
walk(new Cat("Sprinkles"));

(Edit: for symbol kerfuffle)

1

u/moreteam Sep 21 '15

Nice example! Though it might be a bit clearer if you'd assign Symbol("walk") to some identifier in the beginning. As-is the code wouldn't work because you're creating multiple symbols.

1

u/dukerutledge Sep 22 '15 edited Sep 22 '15

Good catch! I originally had it that way and then started thinking in terms of Lisp symbols. Will edit.

1

u/vinnl Sep 22 '15

Excellent explanation, with a very recognisable example.

1

u/e82 Sep 22 '15

One of the nicer simple explanations & example I've seen on this topic.

0

u/I_Pork_Saucy_Ladies Sep 23 '15

Very, very nice explanation of the difference between the two. I completely agree.

But the really big problem with inheritance is that you’re encouraged to predict the future. Inheritance encourages you to build this taxonomy of objects very early on in your project, and you are most likely going to make design mistakes doing that, because humans cannot predict the future (even though it feels like we can), and getting out of these inheritiance taxonomies is a lot harder than getting out of them.

Oh man, I wish people would think more about this in general when developing...

"Well, do we really need a surrogate key for this table? Nah, let's just use a natural key - I mean, how would a social security number ever change? Better save the 3 seconds it takes to create that 'id' column."

Sometimes I wish I could stab people in the face retroactively.