Why have class hierarchies AND module inclusion? (was: Re: Minimal example to change an instance var

On Wed, Sep 18, 2013 at 12:10 PM, Marc H. [email protected]
wrote:

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. :wink:

Kind regards

robert

Robert explains it best. I’ll only throw in a few pence…

Hierarchy and inheritance gives you a sense of solidarity in code.
Design
patterns in Ruby do not differ that much from other languages. Ruby
already
possesses flexibility, but it also lets you lay down the law if you need
to. Many times we have to model other things that require a hierarchy in
order to function. Ruby tries (and succeeds) at giving you the ability
to
have your own design paradigm, and we end up doing that knowing full
well
that our surfboard on that wave is built out of convention.

As Robert hinted at, classes vs. modules says a lot about the difference

and the need for that difference – in scope, and how you might use it
to
your advantage.

On Wed, Sep 18, 2013 at 6:25 AM, Robert K.