Hacker News new | ask | show | jobs
by al2o3cr 4362 days ago
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...

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.

2 comments

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

From the readme of that repo: "It is not suitable for any real purpose ... it may be a fun starting point for palying around with design strategies ... [the compositional design] is probably a bad idea for a number of reasons, but is worth investigating."

When someone explains at length that some code they've put up on github is experimental, probably-a-bad-idea, not-for-serious-use, just-playing-around-with-design-strategies code, deep-linking to it in order to hold it up as an example of 'bad things people are doing nowadays' seems a little uncharitable.

It certainly makes me think twice about putting my own just-for-fun code experiments up on github in the future (without a disclaimer at the top of every file, anyway).

You can only inherit from one class in ruby. You can mixin multiple modules into a class. So they aren't entirely equivalent.
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.