Friday, April 07, 2006

Style and Stanzas

The same piece of code can be written in a thousand ways, and every way has different tradeoffs in terms or readibility, expressiveness, debuggability, verbosity, etc..

Jean-Charles Carelli recently asked on the rubytalk mailing list how to improve on the following style from the pickaxe book:

# 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))

I like a multi-line nested format, that I call Stanza - you know, like in poetry.

It looks like the following:

songs.append Song.new(
                   title,
                   name,
                   duration = ( mins.to_i * 60 + secs.to_i )
             )

It clearly shows you what you are appending as a chunk of code on the right. the 'duration =' idiom makes the intent explicit.  I use brackets to nest conceptual entities (Song, duration), so that they stand out as visually striking, which is useful if you are doing some Gestalt Code Reading.

Sometimes, using metaprogramming I also get rid of the explicit new by wrapping up object instantiation with a Song(..) method on the top level.  I use this Implicit Constructor because I don't want to be concerned with object creation in my code, just with the meaning of the entities that I am manipulating.

songs.append Song(
               title,
               name,
               duration = ( mins.to_i * 60 + secs.to_i )
             )



Comments: Post a Comment

Links to this post:

Create a Link



<< Home

This page is powered by Blogger. Isn't yours?