From: ptkwt@... (Phil Tomson) Date: 2004-08-19T04:51:15+09:00 Subject: Re: When to use parentheses around method args? In article , Richard Dale wrote: >On Patrick Logan's blog he gives a ruby example in discussing design >trade-offs implementing a visitor/decorator pattern with search trees that >are a mixture of elephants and boxes of elephants. > >http://martinfowler.com/bliki/CourtesyImplementation.html > >But I just couldn't work out what the code meant at first - it took me about >5 mins of staring at it before the penny dropped.. > >My problem was the the method: > > def << aNode > @children << aNode > end > >I wondered what is this strange new ruby syntax? But as soon as I saw it >meant this I could follow the code: > > def <<(aNode) > @children << aNode > end > >It's like one of the 'Escher mind teasers' where you seen a cube from one >perspective, and then suddenly your brain flip-flops to another one. > >Are there any rules of thumb for when it's a good idea to leave out the >brackets and when to use them? When I'm defining an operator method (like '<<' in this example) I always put in the parens - it's just clearer. Actually, in general when I'm defining any method I always use the parens. When I call a method, though, I often omit the parens. > >He says it's bad style to use 'if c.kind_of? Elephant', and instead it's >better to expect each node to return a number of elephants. His improved >example expects every node to respond to 'num_elephants', but he makes no >check and so there would be a method_missing execption thrown for a >non-elephant/non-box thing. > >I think the second example would be improved by a respond_to? check, but >what if you expected 'elephant aware nodes' to return you a total elephant >weight? Has anyone suggested adding a 'conforms_to?' check in ruby that >checks that an instance will respond_to? an Array of method name symbols? > I must admit I wasn't satisfied with the solution presented there either. I suppose if you've got a limited number of leaf-type Nodes it's not so bad, but if you've got lots of leaf types then you have to include more methods to handle them. Phil