Composition over Inheritance and other Pithy Catch Phrases

altdotnet design-patterns 0 comments suggest edit

Love them or hate them, the ALT.NET mailing list is a source of interesting debate, commentary and insight. I can’t help myself but to participate. Debate is good. Stifling debate is bad. Period. End of debate. (see!? That was bad!)

The community itself is a young community, and as such, they are going through a period of identity forming. What are their shared values? What does it mean to be an ALT.NET-er? It’s not exactly clear yet, but it is starting to form.

One thing I would caution this community is to be careful in how they define their shared principles. For example, in one thread one individual mentioned debating me and then in the same message proposed the idea of Composition over Inheritance as a shared principle.

In response, someone posted this:

You can throw the book at those people–literally. Favoring composition over inheritance is straight out of the Gang of Four book. Don’t like design patterns? Fine. No problem. I have a couple of Don Box COM+ books that say the exact same thing.

Here was my response, which I also wanted to put in a blog post since it represents pretty well what I think.

I think ALT.NET should focus more on the principles of thinking for yourselfand a desire to improve.

Favoring composition over inheritance is straight out of the Gang of Four book.

So is the Singleton pattern. So is the Template Method pattern.

Sorry, Appeal to Authority doesn’t work for me. Look, I’m not against composition over inheritance in many cases. Perhaps most cases. What I am against is saying that it applies in all cases and that if you don’t do it, you’re not ALT.NET.

I’m against the blind application of these pithy catch phrases. Blindly applying a “best practice” is just as irresponsible as never applying a “best practice”. There is no perfect design. There is no one true way. There is no one size fits all.

Why favor composition over inheritance? What trade-offs are you making when you do so? Developers should think through these things when they make these choices. And when a developer does think through the issue, but makes a choice that differs from what you think, you should applaud that. At least the developer thought through the decision.

I don’t care that a developer doesn’t favor composition over inheritance in a specific case. I only care that the developer thought it through, had a reason for the decision, wants to improve.

The goal is not to bend developers to the will of some specific patterns, but to get them to think about their work and what they are doing. For example, one advantage with inheritance is that it is easier to use than composition. However, that ease of use comes at the cost that it is harder to reuse because the subclass is tied to the parent class.

One advantage of composition is that it is more flexible because behavior can be swapped at runtime. One disadvantage of composition is that the behavior of the system may be harder to understand just by looking at the source. These are all factors one should think about when applying composition over inheritance.

So while I agree that you should favor composition over inheritance, inheritance is still necessary. After all, “the set of components is never quite rich enough in practice.”

That quote is from Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides in Design Patterns. But don’t believe it just because they said it. After all, I would hate to be guilty of an Appeal to Authority. ;)

Found a typo or error? Suggest an edit! If accepted, your contribution is listed automatically here.

Comments

avatar

30 responses

  1. Avatar for Julian Birch
    Julian Birch December 10th, 2007

    Although I agree with everything you say here, I still think it's the single best piece of advice in the whole GoF book. Ironically, it's in the introductory chapter, and I've met plenty of developers who skipped the introduction...

  2. Avatar for Gökhan
    Gökhan December 10th, 2007

    Someone on the very same list once said
    "Design without patterns is the slowest route to victory. Patterns without design is the noise before defeat."
    Original quote was from Sun Tzu, I believe.

  3. Avatar for Damien Guard
    Damien Guard December 10th, 2007

    I wish .NET better supported composition by letting you wire up your interface declaration to a private instance variable for all non-defined methods/properties of that interface.
    I wrote a post about it (right at the end).
    The jist of the syntax would be something like:

    public class CustomerPriceList : IList<ProductPrice> goto productPrice
    {
    private IList<ProductPrice> productPrice = new IList<ProductPrice)();
    public Customer Customer;
    }

    [)amien

  4. Avatar for John Chapman
    John Chapman December 10th, 2007

    I couldn't agree with more with this. I feel that often times people back themselves in to a corner. I have heard others bring this same mantra of "composition is better than inheritance." While it is true that you could typically use one approach against the other, they really best serve different purposes. As a developer we need to be able to find the best tool for a given job. It's the classic saying of "when your only tool is a hammer every problem starts to look like a nail."

  5. Avatar for J. Ambrose Little
    J. Ambrose Little December 10th, 2007

    Far be it from me to put words in Phil's mouth, but I hope that folks recognize that his post about favoring

  6. Avatar for Dave Spake
    Dave Spake December 10th, 2007

    Funnily enough, the GoF book agrees with you. Part of their definition of a design pattern includes Consequence, which they define as the various trade-offs involved in applying that pattern, all of which should be weighed before it is applied. Taking a mantra like "favour composition over inheritance" out of context and using that as an unbending rule not only goes against that philosophy but highlights the dangers of reducing sound advice to the level of soundbites.

  7. Avatar for Larry Clapp
    Larry Clapp December 10th, 2007

    You wrote your rant as if "favor" means "always use". It doesn't, and I don't think that most people think it does. I can *always* favor composition over inheritance, but that doesn't mean I will always *use* composition instead of inheritance. I dunno, I suppose that's the entire point of this entry, but to me it seemed like you are arguing over a straw man.

  8. Avatar for Justin
    Justin December 10th, 2007

    While it is true that most of our community once they have learnt a pattern, regard every problem as a nail to be pounded with their newly crafted hammer, this particular advice is one of the best counterpoints to the legion vast who have yet to realize that inheritance implies an 'is a' relationship rather than a simple way to reuse the code of the superclass.
    Likewise, there is nothing inherently wrong with the singleton pattern, nor the template pattern, each has its merits and it is the inappropriate application of said patterns that cause such great consternation.
    There are far too many absolutes in our community and not nearly enough rational advice, this piece of advise is not one of them, it just needs to be explained in terms of a 'is a' and 'has a', and it makes much more sense.
    In any case, describing a sentence prefixed with the word 'prefer' as 'pithy' seems out of place.

  9. Avatar for ASPInsiders
    ASPInsiders December 10th, 2007

    Far be it from me to put words in Phil's mouth, but I hope that folks recognize that his post about favoring

  10. Avatar for Haacked
    Haacked December 10th, 2007

    @Larry Yeah, I should have pointed out that in various places, when I mention that subclassing is a valid method in some particular case, people have thrown "Composition over Inheritance" at me as an almost automatic response, leaving out the favor part, which I believe is the key word. I changed the title of the post to reflect that.
    As I said, I believe that is good advice. I really do. But to me, following that advice is less important than understanding why it exists. Once you understand it, then I believe in the right cases, you'll make a good choice.
    @Justin I didn't mean to insinuate that Singleton nor Template Method are universally bad patterns. Actually, I like the Template Method pattern. It's a counterpoint to composition because it requires inheritance. It's an example of usability in API design.

  11. Avatar for Troy DeMonbreun
    Troy DeMonbreun December 10th, 2007

    Larry makes a good point, the definition of the word "favor" seems glossed-over. But, maybe Phil is vehement about not even favoring a practice because it is still a rule, even if not black and white.
    As an aside, ALT.NET (the label and the movement) makes me think of the adage "nonconformity _is_ conformity".
    The thing I DO like about ALT.NET is their tendency to, as Phil wishes above that it was their only tendency, "... focus more on the principles of thinking for yourself and a desire to improve."

  12. Avatar for Haacked
    Haacked December 10th, 2007

    @Troy - I cleared that up in my comment to Larry.
    I wouldn't say I wish it was their only tendency. J. Ambrose's post in response to mind understood my point and was a thoughtful response. You can read my comment over there in which I clarified a bit of what I'm thinking.

  13. Avatar for Brennan Stehling
    Brennan Stehling December 11th, 2007

    Sometimes you cannot use inheritance to address your current task. I use inheritance and composition all the time and it comes down to whether or not I can delegate functionality and if inheritance even makes sense. My favorite example of composition is the GridView which extends the CompositeDataBoundControl. It is made up of Buttons, TextBoxes, Labels and all kinds of other controls. It does not inherit them, but instead leverages the properties and events on the child controls to orchestration the actions that are taking place. Meanwhile it can be useful to extend the TextBox control to add new functionality or to override the rendering. I like having both approaches available to me.

  14. Avatar for Sean Chambers
    Sean Chambers December 11th, 2007

    Phil Haack just wrote a post about Composition over Inheritance and how adopting practices just because

  15. Avatar for Ryan Ginstrom
    Ryan Ginstrom December 11th, 2007

    Well, the rule is "favor composition over inheritance," not "blindly apply composition regardless of other factors." As such, I think it's great advice. Maybe not so great as a core value, but definitely advice to heed.

  16. Avatar for Haacked
    Haacked December 11th, 2007

    @Ryan - I agree. I think what I didn't make clear is that it's been thrown at me as "Composition over Inheritance". I'll talk about a case where I believe inheritance is valid and get the response "Composition over Inheritance". Over and over again like a broken record.
    Gread advice. Certainly. Better advice when you understand why it's great advice.

  17. Avatar for Ryan Ginstrom
    Ryan Ginstrom December 11th, 2007

    @Haaked - Definitely in agreement. Blindly applying this "rule" without understanding it is a bad thing.
    Most design rules exist in a state of tension with other rules, the idea being to achieve equilibrium. In the case of "favor composition over inheritance," I think that one of the tensions is with "do the simplest thing TCPW."* Hopefully, the equilibrium point between them is a simple yet extensible system.
    * True for statically typed languages at least

  18. Avatar for Christopher Steen
    Christopher Steen December 11th, 2007

    Link Listing - December 11, 2007

  19. Avatar for Colin Jack
    Colin Jack December 11th, 2007

    Good post and yeah completely agree.

  20. Avatar for Sam Gentile
    Sam Gentile December 11th, 2007

    Prodded by Mike to pick up the slack, I am trying to get one of these out each morning before all my

  21. Avatar for DotNetKicks.com
    DotNetKicks.com December 12th, 2007

    You've been kicked (a good thing) - Trackback from DotNetKicks.com

  22. Avatar for Troy DeMonbreun
    Troy DeMonbreun December 12th, 2007

    @Phil - yeah, what you're seeing was a response that I had in started in my browser before yours had shown up, hence the "Re: Favor..." still in my comment subject even though you changed it before you posted.
    Basically it was a blog post "race condition" concurrency issue. :-)
    Regarding ALT.NET tendencies comment, apologies, I should have said "main" instead of "only", or omitted it altogether.

  23. Avatar for silky
    silky December 12th, 2007

    news at 11: programmers should think for themselves?
    what on earth has our trade come to that posts/comments like this are required? it's sad.

  24. Avatar for Troy DeMonbreun
    Troy DeMonbreun December 12th, 2007

    @silky - sad, but true, and not only occurring in just our trade, but in much of society.
    As in Crowd Psychology, Group Think and
    Sheeple to name a few of the observations about society/human nature.

  25. Avatar for Haacked
    Haacked December 12th, 2007

    @silky I think we *all* need a gentle reminder from time to time. It's easy to get caught up in a movement, a fad, something new. You learn a cool new pattern and start looking for nails to hammer with it. I think it's a natural tendency.
    One that needs to be squashed! ;)

  26. Avatar for Mark Leighton Fisher
    Mark Leighton Fisher December 13th, 2007

    As someone who tries to be a Software Engineer, I'm reminded of the old engineer's phrase: "Good. Fast. Cheap. Pick at most two." Software Engineering is all about making engineering choices -- inheritance vs. composition, build vs. buy, Open vs. Closed Source, etc. Closing off your mind by always picking one alternative means closing off choices that might be better for your particular project (possibly your next project).

  27. Avatar for kNocki
    kNocki September 29th, 2008

    Whoa! (I know this is way late.) What the heck does "Favor" mean anyway?

  28. Avatar for rosyth
    rosyth October 8th, 2008

    Brennan are you from rosyth did u teach P3-youthful? If u do i think u are Mr Joseph(I Am Kester)

  29. Avatar for David Rogers
    David Rogers March 29th, 2010

    (In a world where search engine ordering defines currency, this is a happening conversation.)
    For most junior programmers, blindly adhering to these patterns is likely to produce better designs than ignorance of them. If a junior programmer is doing design work, handing them a list of these pithy phrases and an example or two to demonstrate them is going to be very helpful.
    Teaching junior programmers standards, such as design patterns, is a necessary first step in properly educating them. The wisdom to question patterns and to decide when *not* to use them comes with experience. But note the emphasis here on learning them as quasi-absolutes, aka “Best Practices”.
    Learning “what to think about” is not a necessary first step in learning to think, but I think a lot of time is wasted when such guidance is missing.

  30. Avatar for Rich
    Rich December 1st, 2010

    Gökhan said: "Design without patterns is the slowest route to victory."
    "Patterns mean that you've run out of language" -- Rich Hickey