DEV Community

Iteration Podcast

Composition Imposition

Combining Objects with Composition

Metz, Sandi. Practical Object-Oriented Design in Ruby

A weekly podcast about programming, development, and design through the lens of amazing books, chapter-by-chapter.

“Combining the qualities of two existing subclasses, something that inheritance cannot readily accommodate.”

We talked about inheritance, then modules, now this builds on top of the idea of modules and pushes it further.

Composing a bicycle of parts...

Bicycle > has A parts

Parts has subclasses of - RoadBikeParts and MountainBikeParts

Making the Parts Object More Like an Array - This part was freaky

Parts Factory

Different Configs within the parts factory > an array of all the keys and attributes - road_config - mountain_config

Using all this to make a recumbent bike:

Once this is all set up you have this incredibly powerful interface of a bicycle composed of parts:

Bicycle.new(

size: 'L',

parts: PartsFactory.build(recumbent_config))

Composition VS Aggregation

A Meal is composed of an appetizer - An appetizer does not survive outside of the meal. When the meal is gone by definition the appetizer is gone. A meal is composed of an appetizer.

A band is an aggregate of musicians - when the band breaks up the musicians don’t die.

“Composition” encompasses both aggregation and composition -

“This distinction between composition and aggregation may have a little practical effect on your code.”

Deciding Between Inheritance and Composition

“Think of it this way: For the cost of arranging objects in a hierarchy, you get message delegation for free.”

When in doubt use Composition over inheritance

“The general rule is that faced with a problem that composition can solve, you should be biased towards doing so. If you cannot explicitly defend inheritance as a better solution, use composition.”

John’s Pick: Book: "It Doesn’t Have To Be Crazy At Work" -> David Heinemeier Hansen and Jason Fried

JP: Kahn Academy - digging into math again

Next Week: Final Chapter - Designing Cost-Effective Tests

Episode source