r/programming • u/mortoray • Sep 24 '15
Composition over Inheritance
https://medium.com/humans-create-software/composition-over-inheritance-cb6f880702054
u/juckele Sep 24 '15
Best comment on the article itself
I have been a huge fan of composition for years, although composition and inheritance aren’t mutually exclusive. Your original example works fine until you need to make a MurderRobot that can Bark, so all you have to do is abstract Bark into a barker, and then create a MurderRobotDog class which also composes in the methods of being a barker. Works exactly as you describe, but doesn’t require getting rid of the initial inheritance pattern which still works so well.
At least in the Java world, creating delegates which do the jobs specified by an interface is just a dandy way to go about this.
2
u/CyclonusRIP Sep 24 '15
I think that's they way you go about it in nearly any type safe language. If you have a bunch of classes that implement certain methods and want to interact with them as a group you need a type that encompasses that shared functionality. If you have two classes that require the same implementation of method then make a delegate that they both call. If your class starts to become bloated then decompose it into several delegates. Composition and inheritance aren't at odds. They are two complimentary ways to structure your code.
11
u/vincentk Sep 24 '15
My personal rule of thumb: prefer composition over inheritance, prefer inheritance over copy/paste.
-12
u/Cuddlefluff_Grim Sep 24 '15
My personal rule of thumb : Use whatever is the best fit for any given scenario
18
u/quiI Sep 24 '15
A fairly worthless statement, just like when people say "use the right tool for the right job".
You don't say?
-2
u/Cuddlefluff_Grim Sep 24 '15
I thought the concept was so clearly obvious that people would realize that it was a joke
15
u/Berberberber Sep 24 '15
My personal rule of thumb: a sufficiently vague platitude serves in all cases.
4
13
Sep 24 '15
[removed] — view removed comment
8
u/Deto Sep 24 '15
Yeah, if two methods just happen to be similar, it's not worth it to parameterize the thing and wrap the objects in some wacky inheritance structure just to avoid the code duplication. The two methods will probably just evolve along different paths over time and you'll find yourself doing gymnastics to keep up the nonsensical inheritance structure.
1
u/sirin3 Sep 24 '15
It is not even worth if the methods happen identical
Three identical methods is my rule of thumb
2
3
u/dukerutledge Sep 24 '15
I commented on the previous /r/node thread https://www.reddit.com/r/node/comments/3luto3/composition_over_inheritance/ with this:
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"));3
u/deja-roo Sep 24 '15 edited Sep 24 '15
Um...
You're still going to put all this together, and then refactor the dog and cat to be an animal that is a pooper.
I don't think this guy fully understands the concepts he's demonstrating.
3
2
u/logged_in_for_this Sep 24 '15
So when using a composition, objects have state and agents that act upon that state?
9
u/vincentk Sep 24 '15
The gist of composition over inheritance is the following: If your problem can be decomposed into sub-problems, it's good to solve them one by one. The solution will be the composition of the solutions to the sub-problems.
It tends to be good style to explicitly represent any such structure in your code.
One way to do that in an OO setting is to acknowledge that objects have reasonably well-defined boundaries, and so you can attempt to trace out the structure of your solution by way of object boundaries. If however you use inheritance (in the sense of implementation inheritance), then the boundaries are much more fluid and may in fact be undefined or context-specific.
5
Sep 24 '15 edited Sep 24 '15
So when using a composition, objects have state and agents that act upon that state?
This is not a concept in composition. In composition, every object has its own state, and objects communicate with each other only through their intended public API.
What the author of that video is demonstrating is mix-ins, and "state.foo" stands for "this.foo", because the code examples are avoiding using "this" for some reason.
2
u/iopq Sep 24 '15
Rust doesn't have inheritance (yet) in the classical Java sense, but I have not reached for it. I don't see the point. I'm writing a Go AI and everything is done through composition.
I believe some of the core team complained that the DOM can more easily be represented with inheritance, but I can't comment on that. There is no inheritance in Rust yet, so I'm not sure if they still want it.
6
Sep 24 '15
Inheritance should mostly boil down to interfaces that specify common functionality and provide shared default implementation. Both of which Rust solves with traits (I think they added default implementation to traits - right ?) - so yea - it's solving the same problem with a different but still similar tool.
The actual inheritance model of C++ or w/e is less relevant - you still have the same design problem - do I make Foo implement trait Bar/Baz or do I separate Bar/Baz implementations to new types and make them members of Foo.
6
u/mus1Kk Sep 24 '15
Traits can have implementations and structs using those traits can redefine them. What Rust lacks is inheritance of data; you cannot have one struct inherit from another. At least the last time I checked it. It's a much requested feature though and I'm sure we'll see it in the foreseeable future.
2
Sep 24 '15
Sure but the point is that the problem OP states isn't related to that - it applies to traits as well.
1
u/fuzzynyanko Sep 24 '15
A lot of the program can be broken down to commands. Still, one thing I don't like about this is trying to predict the future, as he mentioned
0
Sep 24 '15
[deleted]
0
Sep 24 '15
[deleted]
1
u/pakoito Sep 24 '15
It's not about the JavaScript hate, it's that's a poor choice to display the concept as proper inheritance is not one of its features.
85
u/[deleted] Sep 24 '15 edited Sep 24 '15
I'd just like to point out, the author isn't demonstrating Composition over Inheritance, but Multiple Inheritance over Single Inheritance. So the whole deliberation later in the video about when to use, or prefer composition over inheritance is kind of pointless, given he's confused about what composition is.
Merging objects together is essentially a form of multiple inheritance (or more casually: "traits" or "mix-ins"). When people talk about composition they mean one object having other objects as properties and using those "sub-objects" to achieve a higher goal.
The benefit of composition is that every object retains its encapsulation, and you eliminate the risk of collisions that's present when you merge objects (say Cat adds method "kill" and you merge it with Robot which has method "kill"... problem).
EDIT: And one more note. Because JS doesn't support true multiple inheritance, using Object.assign() has another implication, in that instanceof checks won't return true when checking an object against its parent types.
Whether this matters is up to your design, but I wouldn't give it up so easily and say it's useless. Inheritance, mix-ins and composition are three distinct strategies with distinct pros, cons and uses. The issues come from not knowing what their proper uses are.