DEV Community

Iteration Podcast

Modules! Modules! Modules!

Metz, Sandi. Practical Object-Oriented Design in Ruby

Chapter 7. Sharing Role Behavior with Modules

Welcome to iteration

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

Modules! Modules! Modules!

Last episode we talked about inheritance which was kind of an extension of duck typing… but sometimes we need to combine the qualities of two existing subclasses, something that inheritance cannot readily accommodate.

Many object-oriented languages provide a way to define a named group of methods that are independent of class and can be mixed in to any object. In Ruby, these mix-ins are called modules.

Discovering the Schedulable Duck Type

The Schedule expects its target to behave like something that understands lead_days, that is, like something that is “schedulable.” You have discovered a duck type.

This specific example illustrates the general idea that objects should manage themselves; they should contain their own behavior.

Mountain Bike? Mechanic?

Now, in the code above, the dependency on Schedule has been removed from Bicycle and moved into the Schedulable module, isolating it even further.

Like Using Inheritance

COMES BACK TO AUTOMATIC MESSAGE DELEGATION

Loggable Example

When Bicycle includes Schedulable, all of the methods defined in the module become part of Bicycle’s response set.

When a single class includes several different modules, the modules are placed in the method lookup path in reverse order of module inclusion. Thus, the methods of the last included module are encountered first in the lookup path.

When a single class includes several different modules, the modules are placed in the method lookup path in reverse order of module inclusion. Thus, the methods of the last included module are encountered first in the lookup path.

Picks:

John: Type to Siri - Accessibility > Siri > Type to Siri

JP: Scrimba - https://scrimba.com/playlist/pKwrCg

Episode source