Filip Bartuzi Filip Bartuzi - 5 months ago 14
Ruby Question

return early vs if in ruby code

I see two styles of writing the same thing:

def find_nest(animal)
return unless animal.bird?
GPS.find_nest(animal.do_crazy_stuff)
end


vs

def find_nest(animal)
if animal.bird?
GPS.find_nest(animal.do_crazy_stuff)
end
end


Which one is more correct/preferable/following-best-practises? Or it does not matter?

Answer

As per Ruby style guide,

Prefer a guard clause when you can assert invalid data. A guard clause is a conditional statement at the top of a function that bails out as soon as it can.

# bad
def compute_thing(thing)
  if thing[:foo]
    update_with_bar(thing)
    if thing[:foo][:bar]
      partial_compute(thing)
    else
      re_compute(thing)
    end
  end
end

# good
def compute_thing(thing)
  return unless thing[:foo]
  update_with_bar(thing[:foo])
  return re_compute(thing) unless thing[:foo][:bar]
  partial_compute(thing)
end