OO Design Patterns: Composition Vs. Inheritance

Lucas PenzeyMoog
The Startup
Published in
7 min readJun 7, 2019

--

As seems to be the case with every apprentice’s technical blog, it’s now my turn to write-up a post comparing and contrasting two staples of Object Oriented software design: composition and inheritance.

The first language I worked in for any meaningful amount of time was Ruby, which is of course Object Oriented. Even before I really understood inheritance or composition, I heard the phrase “prefer composition over inheritance” numerous times. Over time this morphed into “avoid inheritance” in my mental schema regarding OO languages, which I see echoed in numerous technical blogs across the internet.

However, I think that inheritance sometimes gets an unfair shake. As with everything in software engineering, making a decision involves a careful weighing of tradeoffs. Sandi Metz, the guru of OO design patterns and all around wellspring of programming wisdom, explains it succinctly:

“Every decision you make introduces two costs — one to implement it and another to change it when you discover that you were wrong” — Practical Object Oriented Design in Ruby (POODR), Sandi Metz

Notice how she says “when” you are wrong, not “if” you are wrong. This is a good philosophy to keep in the back of your mind when deciding which path to take for any given decision, but it relates directly to why…

--

--