This post originated from an RSS feed registered with Ruby Buzz
by Jeremy Voorhis.
Original Post: On Writing Well: Exposition or Code
Feed Title: JVoorhis
Feed URL: http://feeds.feedburner.com/jvoorhis
Feed Description: JVoorhis is a Rubyist in northeast Ohio. He rambles about Ruby on Rails, development practices, other frameworks such as Django, and on other days he is just full of snark.
When I signed on with O’Reilly Media to write Rails In a Nutshell, I was sent a welcome package that included an audio recording of On Writing Well. One idea that On Writing Well stresses is that you can improve anything you write by cutting 50% of it. The recording even includes a stopping point where the listener is to stop and shorten the last thing he or she has written by 50%.
PuneRuby has posted an interview with Jean-Christian Fischer that I will quote:
I have the 50% rule as a measure of success: I���m usually able to reduce code I have written by 50% by applying better ruby techniques. I try to do that on my code and rejoice when I���m able to achieve that reduction.
I agree. Although some programmers might think this means obfuscation, Ruby offers many ways to cut your code and make it more acceptable. Some places to start:
Only use return when you really need multiple return paths.
Can you rewrite a conditional statement with a modifier?
Are you trapping an exception within a begin block? Do you really need that extra scope? Example: replace
def catch_a_fish
begin
@line.cast
rescue InsufficientBaitError
@line.replenish_bait
end
end
with
def catch_a_fish
@line.cast
rescue InsufficientBaitError
@line.replenish_bait
end
Are you handling an exception? Can you use the rescue modifier? Example: replace
def deep_copy
@widgets.map do |w|
begin
w.dup
rescue
w
end
end
end
with
def deep_copy
@widgets.map { |w| w.dup rescue w }
end
Can you rewrite a simple call to Enumerable#map with Symbol#to_proc? Rewrite
@objects.map { |o| o.attribute }
as
@objects.map &:attribute
Ruby has many syntactical elements that help you write denser, more readable code. Experiment and see what matches your taste, and more importantly, contributes to readability.