On Wed, Sep 18, 2013 at 12:10 PM, Marc H. [email protected]
But this brings me to another question, actually …
Why do we really use subclasses in Ruby when there are almost
completely legit alternative uses to do the same with modules?
That is almost as if there are two different ways to do (almost)
the same and I am unsure whether this is really what matz always
intended? But perhaps I am wrong … it just feels as if there
are two ways to do quite the same…
There are indeed some overlaps in functionality but I believe classes
and modules are different enough to warrant having both. The most
prominent distinction is of course that you cannot instantiate
modules. That is a nice property when using them as namespaces where
they fit better than classes because of this.
More abstractly modules encapsulate functionality: you can view
typical examples like Enumerable as instances of template method
pattern. Enumerable methods depend on method #each being there to do
their work. Method #each is implemented in totally different ways in
different classes but since it’s contract is adhered to by all
implementations (hopefully) Enumerable’s methods can do their job for
all of these classes.
Classes on the other hand represent entities, parts of a model of the
real world problem space that you model. (Note that “real” in this
case also includes intangible things like “HTTP connection”.)
Both classes and modules can represent a set of properties
(attr_accessor generated methods and friends). In case of a module
these properties can be attached to arbitrary classes (if name clashes
are avoided). In case of classes only the class and its subclasses
have this exact set of properties. (You can of course define another
class with the same set of getters and setters but in that case a
module might be in order which contains all the properties and the
code which uses it.) As always, take with a grain of salt.