Fil*_*uzi 5 ruby coding-style guard-clause
我看到两种写同样的东西:
def find_nest(animal)
return unless animal.bird?
GPS.find_nest(animal.do_crazy_stuff)
end
Run Code Online (Sandbox Code Playgroud)
VS
def find_nest(animal)
if animal.bird?
GPS.find_nest(animal.do_crazy_stuff)
end
end
Run Code Online (Sandbox Code Playgroud)
哪一个更正确/更可取/遵循最佳实践?或者没关系?
Wan*_*ker 19
根据Ruby风格指南,
当您可以断言无效数据时,首选保护条款.保护子句是函数顶部的条件语句,可以尽快退出.
Run Code Online (Sandbox Code Playgroud)# 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
Run Code Online (Sandbox Code Playgroud)