This post originated from an RSS feed registered with Ruby Buzz
by Daniel Berger.
Original Post: The single return value approach
Feed Title: Testing 1,2,3...
Feed URL: http://djberg96.livejournal.com/data/rss
Feed Description: A blog on Ruby and other stuff.
A while back I read in a blog, I forget which one, that methods/functions should have only have a single return value. Or rather, that there should only be a single return statement. Or perhaps they meant both.
In any case, the first time I read this I think I dismissed it as too rigid. "Ruby is a dynamic language! I'll do whatever I damned well please!", I told myself. However, the concept knawed at me, so I decided to take that approach in my Ruby code to see how I liked it. The result? I have to admit that it has improved my code somewhat. I end up with code that's a little less verbose (in terms of LOC) and a little easier to read.
Consider this real life example I refactored from net-pingsimple. Here's the original code:
class PingUDP < PingSimple
attr_accessor :data
def ping
super
u = UDPSocket.open
a = []
begin
Timeout.timeout(@timeout){
u.connect(@host,@port)
u.send(@data,0)
a = u.recvfrom(64)
}
if a[0] != @data
return false
end
rescue TimeoutError => t
@exception = t
return false
else
return true
end
end
alias ping? ping
end
That code has three different return statements, with two possible return values (true or false). Now, let's reduce that to a single return value:
class PingUDP < PingSimple
attr_accessor :data
def ping
super
success = false
u = UDPSocket.open
a = []
begin
Timeout.timeout(@timeout){
u.connect(@host,@port)
u.send(@data,0)
a = u.recvfrom(64)
}
rescue TimeoutError => t
@exception = t
else
if a[0] == @data
success = true
end
end
success
end
alias ping? ping
end
Ok, so this particular example didn't save me anything in terms of LOC, but it does look and feel cleaner IMHO. In other classes, such as PingExternal, I do save about 3 lines of code.
I guess I'm just wondering out loud what other folks think of the "single return value" philosophy.