From: Ryan Bates Date: 2006-04-06T08:01:04+09:00 Subject: Re: best practices On Apr 5, 2006, at 2:40 PM, Benjohn Barnes wrote: > :) I choose the third way. I find the first approach too long, and > I dislike unnecessary intermediate values of the second. > > My approach is to factor out the computation of duration in to a > separate method: > def duration; mins.to_s * 60 + secs.to_i; end > > Allowing me to write the call as: > songs.append(Song.new(title, name, duration)) > > I find this helps to make code highly self documenting in many cases. I prefer that method as well. IIRC, Martin Fowler also recommends this (reducing the number of variables) in his Refactoring book. This may cause performance loss, but optimize later when you know it's a problem; and don't let it keep you from making pretty code. There are always exceptions of course, and I think it may be a little over-kill for the simple example, but use your own judgement. Ryan On Apr 5, 2006, at 2:40 PM, Benjohn Barnes wrote: > > On 5 Apr 2006, at 21:39, Jean-Charles Carelli wrote: > >> I'm working my way through the Pickaxe book and I have a question >> regarding syntax and best practices. >> >> Example from page 64 >> >> # 1 Book example >> songs.append(Song.new(title, name, mins.to_i * 60 + secs.to_i)) >> >> >> # 2 Alternate version. >> duration = mins.to_i * 60 + secs.to_i >> songs.append(Song.new(title, name, duration)) >> >> >> Version 1 is very concise but harder to read. Ruby is very >> intuitive but I find the second example easier to read. What is >> everyone else doing? > > :) I choose the third way. I find the first approach too long, and > I dislike unnecessary intermediate values of the second. > > My approach is to factor out the computation of duration in to a > separate method: > def duration; mins.to_s * 60 + secs.to_i; end > > Allowing me to write the call as: > songs.append(Song.new(title, name, duration)) > > I find this helps to make code highly self documenting in many cases. > > Cheers, > Benjohn > >