Hacker News new | ask | show | jobs
by jerf 4359 days ago
Many of us still learned about OO in school, where inheritance was all but beaten into us, and composition was not mentioned. And based on what I've seen in interviews, this is still a common model taught in school. Composition is in the process of winning as the default method of composing things together in OO (see, for instance, Go), but it has not won yet.

And on the topic of Go, note how most common OO languages in use still have more convenient support for inheritance than composition, where "inheritance" is one token in the right place but "composition" takes a lot more boilerplate because there's no support built in, or you have to add a third-party library to make the boilerplate go away. Again, changing over time, but languages change slowly.

1 comments

Composition always takes more boilerplate, because inheritance is noting more than composition with a bunch of default choices for a privileged component (single inheritance) or arbitrary sorting of components (multiple inheritance) made so the programmer doesn't have to write them (but also loses control).
Expanding on shanemhansen's point, where in Python subclassing is just a matter of mentioning the superclass in the right place in the class construct but composition requires substantial boilerplate, in Go, composition is just a matter of mentioning the composed element in the struct definition and inheritance requires a lot of manual boilerplate. It isn't technically impossible to implement something that is as much "inheritance" as it is in Perl, or especially as much "inheritance" as it is in Javascript, which I say with full knowledge of the object model in Javascript, but you will have to implement it yourself. (Courtesy of the lack of generics you won't even be able to factor out the boilerplate very well.) Whereas composing two things together is as easy as:

    type TwoComposedThings struct {
       ThingOne
       ThingTwo
    }
where ThingOne and ThingTwo are types. If ThingOne and ThingTwo do not have any conflicting method names, you're done. (If they do, you can actually still compile but when you try to use a conflicting name you'll have to manually disambiguate, and some subtleties could arise.)
Go chose to have composition as a first class citizen rather than OO. It's called struct embedding. Embedding requires minimal boilerplate.