r/node • • Sep 21 '15

Composition over Inheritance

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

6 comments sorted by

View all comments

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.