gpt4 book ai didi

java - 代码风格 : multiple returns

转载 作者:行者123 更新时间:2023-11-29 08:10:39 25 4
gpt4 key购买 nike

我正在按照这些思路编写方法:

if (hasFoo()) {
return calculateFoo();
} else if (hasBar()) {
return calculateBar();
} else {
return calculateBaz();
}

getter 相当昂贵,has...() 检查要么重复很多逻辑,要么只需要重用 getter。我可以让 has...() 方法将 get...() 的结果存储在一个字段中并使 getter 变得懒惰,但这会很好因为 has...() 没有任何副作用。我可以用嵌套的 try{} catch{} block 来编写它,但这看起来并不优雅。似乎应该有更好的解决方案......

编辑:将 get...() 更改为 calculate...() 以表明它们很昂贵。

最佳答案

int result = 0;

if (hasFoo()) {
result = getFoo();
} else if (hasBar()) {
result = getBar();
} else {
result = getBaz();
}

return result;

是我更喜欢使用的习惯用法 - 使得在调试时检查变量值变得更加容易。

关于java - 代码风格 : multiple returns,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8294729/

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