Hacker News new | ask | show | jobs
by judk 4359 days ago
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).
2 comments

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.