Given that Ilias lately asks so many pseudo-intellectual questions, I’ve
been thinking that I could do the same.
Basically, my gripe is that Ruby separates behaviour into module and
classes.
It is extremely typical to see code like:
module Foo
class Bar
Foo::Bar.new
Now, let’s model an animal hierarchy for a moment …
class Animal
has some code
class Cat < Animal
has some code
class Dog < Animal
has some code
class Fox < Animal
has some code
Ok, they all use Animal. But is it really needed to subclass like that?
Wouldn’t it be just as useful to do this:
class Animal
class Cat
include Animal
class Dog
include Animal
And so on? In other words to include another class into a class, just as
if it were a module.
But it could be simplified even more. Why is there any distinction
between class and module, seriously?
module Animal
define some common methods
class Cat
include Animal
Of course because a module is an incomplete class only. It won’t have
instance variables and so on. But why not? It is just behaviour after
all, and a class that includes a module can behave differently
afterwards, almost the same way as you get by subclassing.
I feel that when I think about subclassing, I just restrict the way I
model something. It only follows a one-way path, down the line.
Animal -> Cat -> Tom
Tom the cat.
He would have the functionality of Cat and Animals.
But what if Tom also wants to be… let’s say … an undead cat?
Well … I guess being an undead cat, one would have to be a module.
module Undead
Animal -> Cat -> Tom -> include Undead
Or of course, Cat could be changed to UndeadCat
Animal -> UndeadCat -> Tom
But that would force me to use a new cat type, and I’d rather do that
differently too.
Animal -> Cat -> include Undead -> Tom
I am not sure if I am making a lot of sense here.
My main questions are:
-
Why is there a real distinction between module and class in Ruby in
the first place? -
What advantages does that bring, or rather, why would it be not
possible to harmonize both class and modules into the same thing,
behaviours or traits? (Or perhaps, to think of Ruby as a prototype based
language and just use traits to extend those objects WITHOUT any
subclassing )