Thursday, March 15, 2007

Module

Like classes, modules are bundles of methods and constants.
Unlike classes, modules don’t have instances; instead, you specify that you want the functionality of a particular module to be added to the functionality of a class, or of a specific object.

It’s no accident that modules are similar in many respects to classes: The class Class is a subclass of Module. Judging by the family tree of classes, class is a specialized form of module.

We saw that Object is the highest class; here, we’ll meet the highest module: Kernel.

When you write a class, you then create instances of the class. Those instances can execute the class’s instance methods.
Modules, however, don’t have instances. Instead, modules get mixed in to classes.
When this happens, the instance of the class has the ability to call instance methods defined in the module.
Modules are sometimes referred to as mix-ins.

The mix-in operation is achieved with the include statement. include is actually a method.

The main difference between inheriting from a class and mixing in a module is that you can mix in more than one module.
No class can inherit from more than one class. In cases where you want numerous extra behaviors for a class’s instances—and you don’t want to stash them all into the class’s superclass—you can use modules to organize your code in a more granular way. Each module can add something different to the methods available through the class.

When to use Module?

Modules open up lots of possibilities, particularly for sharing code among more than one class , because any number of classes can mix in the same module.

The greatest strength of modules is that they help you with program design and flexibility.

Modules encourage modular design: program design that breaks large components into smaller ones and lets you mix and match object behaviors.

When you’re designing a program and you identify a behavior or set of behaviors that may be exhibited by more than one kind of entity or object, you’ve found a good candidate for a module.

1 comment:

I love soy sauce said...

Oh my gosh, thank you for this post. I can see the light!