Chapter 9. Mixins: Mix It Up

Inheritance has its limitations. You can only inherit methods from one class. But what if you need to share several sets of behavior across several classes? Like methods for starting a battery charge cycle and reporting its charge level—you might need those methods on phones, power drills, and electric cars. Are you going to create a single superclass for all of those? (It won’t end well if you try.) Or methods for starting and stopping a motor. Sure, the drill and the car might need those, but the phone won’t!
In this chapter, we’ll learn about modules and mixins, a powerful way to group methods together and then share them only with particular classes that need them.
The media-sharing app
This week’s client project is an app for sharing videos, music, and other media. Music and videos both need some of the same functionality: users need to be able to play songs and videos back, as well as leave comments on them. (To keep this example simple, we’ll omit functionality like pausing, rewinding, etc.)

There are some aspects that differ, however. We need the ability to track the number of beats per minute on songs, to separate the fast music from the slow music. Videos don’t need a number of beats per minute, but they do need to keep track of their resolution (how ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access