I saw something like this this library:
class A
# ...
class B < A
# ...
end
end
Is this not weird? I get the concept that you can declare classes inside other classes, but those nested classes inherit from the parent one. Is that not like an infinite loop?
Maybe it is simpler than it looks like, but this image makes me hesitate a lot. Am I missing some hiding benefit here, or a special Ruby idiom that I do not know?
Namespace and subclassing are two different things. They have no relation to each other.
By doing:
class A
class B
end
end
you define B in the namespace of A, hence A::B (but B is not a subclass of A; in fact it is a subclass of Object).
By doing:
class A
end
class B < A
end
you define B as a subclass of A (but B is not in the namespace of A; in fact it is in the namespace of the main environment :: (or Object::).
In your example:
class A
class B < A
end
end
both happened simultaneously, but they are independent of one another, and there is no contradiction.
In addition to @sawa's answer: this can be useful as an intermediate step during refactoring.
Say, I come across some big fat class and I clearly see that several subclasses can be extracted here. But I don't know their names yet. And when I do, I might rename them several times in the process. This makes creating a file for each subclass an unnecessary hurdle. So I start with declaring subclasses right there, and move code within the same file. When I'm somewhat satisfied, then I will move the subclasses to their dedicated files. Or maybe I will not, if they are very small (and I'm feeling that they don't deserve a separate file).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With