return 早期 vs ruby 代码

return early vs if in ruby code

我看到两种写法是一样的:

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

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

哪个更correct/preferable/following-best-practises?还是无所谓?

根据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

这显然是个人喜好问题。不过我更喜欢早期的return。它不仅使代码 "flatter" 更易于阅读,而且还可以很好地扩展检查次数。例如:

  def create_terms_of_service_notification
    return if Rails.env.test?
    return if current_user.accepted_tos?
    # imagine 5 more checks here. 
    # Now imagine them as a mess of nested ifs.

    # create the notification
  end

这个:}

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