# 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
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
3条答案
按热度按时间cyvaqqii1#
根据Ruby风格指南,
当您可以Assert无效数据时,首选保护子句。保护子句是位于函数顶部的条件语句,它会尽快退出。
vjhs03f72#
这显然是个人喜好的问题。但我更喜欢早点回来。它不仅使代码“更扁平”,更容易阅读,而且还可以很好地扩展检查的数量。举例来说:
p3rjfoxz3#
这:}