I try to create methods that bail out early if conditions aren't met, flattening the code in terms of indentation:
def find_something data
return unless data.has_what_we_need?
a = data.something
return unless a.has_what_we_want?
a.the_stuff[42]
end
This has two well defined exit points, as return
should show up as a fairly obvious thing when reading it. A return
with no argument will return nil
to the caller.
If you don't care about nil
vs. false
you can condense this even more:
def find_something data
return unless data.has_what_we_need?
a = data.something
a.has_what_we_want? and a.the_stuff[42]
end