6

我看到两种写同一件事的方式:

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

哪一个更正确/更可取/遵循最佳实践?还是没关系?

4

3 回答 3

24

根据Ruby 风格指南

当您可以断言无效数据时,首选保护子句。保护子句是函数顶部的条件语句,它会尽快退出。

# 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
于 2016-06-17T11:44:47.673 回答
5

这显然是个人喜好问题。但我更喜欢早点回来。它不仅使代码“更扁平”且更易于阅读,而且还可以很好地适应检查次数。例如:

  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
于 2016-06-17T11:46:00.157 回答
0

这 :}

def find_nest(animal)
  GPS.find_nest(animal.do_crazy_stuff) if animal.bird?
end
于 2016-08-04T10:14:50.587 回答