|
|
|
|
|
by mattfenwick
4307 days ago
|
|
It's difficult to see the point because it's not a very good example. Why do Elephants inherit from Node (they seem entirely unrelated)? How can I put things other than Elephants in boxes -- by also having them inherit from Node? Why isn't there a "Leaf" subclass of Node that contains one of anything? I think the tradeoff between adding methods to a class hierarchy and adding cases to functions is relevant here (I think this is known as the expression problem -- http://en.wikipedia.org/wiki/Expression_problem -- but I'm not sure), but it's not mentioned: > Now the kind_of? test in num_elephants is a smell, since we should be wary of any conditional that tests the type of an object. |
|
And, since it's ruby, the answer to "how can I put things other than Elephants in boxes", with the current code example, is "just make sure they have a #num_elephants method". Which, yeah, seems kind of insane, although part of that is the artificial example.
An IMO better solution still within this kind of OO world would be to declare an interface of some kind "CountableNode" or something, and say, anything you put in a box has to implement that interface (which to begin with has one method, #num_elephants). There are ways to do that sort of thing in ruby (there are ways to do almost anything in ruby), but they aren't done very often in rubyland, which I do think is a failing in the ruby idiom. Although many rubyists will say they've never found it a problem in practice (maybe they're right, maybe they just didn't recognize the root of the problems they did have).
Anyway, you make reasonable points even with these 'corrections', but Fowler could have made his example a bit tighter while still staying firmly within conventional ruby and/or OO best practices.