gpt4 book ai didi

ruby - 提前返回 vs if 在 ruby​​ 代码中

转载 作者:数据小太阳 更新时间:2023-10-29 07:09:04 26 4
gpt4 key购买 nike

我看到有两种写作风格:

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

哪个更正确/更可取/遵循最佳实践?还是无所谓?

最佳答案

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

关于ruby - 提前返回 vs if 在 ruby​​ 代码中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37880676/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com