4 ms·
>4. If composition is not enough go through all other similar design patterns that are not based on inheritance. IMO, that seems like too formulaic an approach
by vram22 6y ago
>4. If composition is not enough go through all other similar design patterns that are not based on inheritance.
IMO, that seems like too formulaic an approach without enough thinking in that step.
Also, you mention design patterns, but the classic design pattern book nicknamed GoF (Gang of Four, i.e. by Gamma, Vlissides et al), has this guideline prominently on an early page (before the main body of text):
"Prefer composition over inheritance"
, or similar words (from memory).
And that is the only sentence on that page, right in the middle, which could only have been done for great emphasis.
But you say:
3. If interfaces are not enough, use composition
And although you do say to avoid inheritance, aren't interfaces somewhat similar to inheritance, so shouldn't the same GoF guideline apply?
Asking for myself.
- arunix 6y agoMy copy of the GoF book does not have that sentence as the only one on it's page, however there are only two guiding principles mentioned in chapter one, the other one being: "Program to an interface, not an implementation" and this actually comes before the other one about composition. Inheritance (i.e. implementation inheritance) creates tight coupling between classes, whereas interfaces exist to prevent that happening, ... they are quite different constructs.
- jgwil2 6y agoAgree, and would just add that interface inheritance can be useful too and is not the quagmire that implementation inheritance is.
- vram22 6y agoI'm almost sure that my copy of the GoF book did have that sentence as the only one on its page, and as I said earlier, it was on a separate page before the main body of text, i.e. even before chapter one. Maybe we have different editions. Could still be wrong about that, though. E.g. it could been a different book, not GoF, although I think it unlikely. Why I say that I remember it being so, is because I once mentioned this to a startup founder I was consulting to, maybe because he had written some code that used inheritance unnecessarily, and I said it to him in that context, during a design discussion, and suggested we follow the guideline (to prefer composition over inheritance). He was impressed (I mean by the guideline, not me) and we did follow it from then on.