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 agree with Jeff Cohen on the refactoring if (as James Britt points out) you find yourself repeating this code in anyway. I also
agree with Benjohn Barnes on the use of a duration method, although i think it belong on Song, and not just as some generic.
def duration; @mins.to_s * 60 + @secs.to_i; end
songs.append(Song.new(title, name, duration))
The above code doesn't work for me. Duration is a responsibility of the Song IMO. Move duration as an instance method on Song, and
then forget about it elsewhere. This is of course if you have to constantly calculate the duration for the Song constructor. If
you always have minutes and seconds and have to compute the duration, why not just let Song take care of it for you? Do you ever
just know the "duration" without having to calculate it ?
class Song
def duration; @mins.to_s * 60 + @secs.to_i; end
def initialize( title, name, minutes, seconds )
@title, @name, @min, @secs = title, name, minutes, seconds
end
end
Zach