liveBook · Manning

Modularity

As explained in The Well-Grounded Rubyist, Fourth Edition

Modularization is the organization of software functionality into separate reusable modules.

Modularity organizes software functionality into separate, reusable modules. In Ruby, modules bundle methods and constants, then add those behaviors to classes or individual objects rather than creating instances themselves. section 4.0

The practical benefit appears when one general behavior applies to several classes. A class can include a module and gain its methods without duplicating their implementations. section 4.1.2

Modularity in Ruby supports several related design goals:

Making a class stacklike

A Stack class can include Stacklike and expose add_to_stack, take_from_stack, and stack. Running the resulting object adds three items, removes the last one, and leaves the earlier two. A nonmodular Stack implementation produces the same behavior, but the module makes stacklikeness reusable for other cases. section 4.1.2

Listing 4.2 Mixing the Stacklike module into the Stack class
require_relative "stacklike"   1
class Stack
  include Stacklike      2
end

Ruby mixes a module into a class with include, allowing Stack to acquire Stacklike behavior. section 4.1.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains modules through class comparison and a Stack mixin, while signposting deeper method-lookup mechanics.
Examples
Uses a Stacklike module, a Stack class, include, and equivalent modular and nonmodular implementations.
What it assumes
Assumes familiarity with Ruby classes and objects while teaching modules, their lack of instances, and their relationship to classes.
What you can do after
Apply Ruby modules with include to share a general behavior across multiple classes without duplicating implementation.
How it connects
Connects modularity with modules, classes, encapsulation, mixins, namespaces, and method lookup.

Also explained in

Compare how 10 books explain modularity →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.