gpt4 book ai didi

coding-style - if : to nest or not to nest 的样式

转载 作者:行者123 更新时间:2023-12-04 09:38:02 27 4
gpt4 key购买 nike

我和我的一位同事就以下最佳实践问题进行了讨论。
大多数函数/方法都从一些参数检查开始。

我提倡以下风格,避免嵌套。

if (parameter one is ugly) return ERROR;
if (parameter two is nonsense || it is raining) return ERROR;
// do the useful stuff
return result;

来自更多函数/逻辑编程背景的他更喜欢以下内容,因为它减少了函数退出点的数量。
if (parameter one is ok) {
if (parameter two is ok && the sun is shining) {
// do the useful stuff
return result
}
}
return ERROR;

你更喜欢哪一个,为什么?

最佳答案

我个人更喜欢第一种风格,因为我觉得它在我们所谓的“错误案例”和“方法逻辑”之间提供了一些逻辑上的分离。在方法的开头有一个定义明确的块,用于评估和处理输入中的任何错误,然后方法的其余部分都是关于方法实际应该做什么的。

我想这是微观层面上某种关注点的分离。

关于coding-style - if : to nest or not to nest 的样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2911960/

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