将结果存储在临时变量中而不是多个返回点 [英] Storing result in a temp variable versus multiple return points
问题描述
一般来说,哪种做法更好,为什么?在什么情况下你会改变主意?
Which is a better practice, generally speaking, and why? Under what circumstances would you change your mind?
function foo1(int x) {
int result;
if (x > 5) {
result = 2;
} else {
result = 7;
}
return result;
}
或
function foo2(int x) {
if (x > 5) {
return 2;
} else {
return 7;
}
}
推荐答案
我更喜欢第二种形式,您只需立即返回即可.我所知道的唯一考虑如下.好处:
I prefer the second form where you just return immediately. The only considerations I'm aware of are as follows. Benefits:
- 更短的代码
- 更容易关注
- 更少的变量(我猜是更容易理解的一部分)
风险:
- 可以跳过返回后发生的清理处理
我不太担心风险,因为如果您在尝试管理保留返回值的各种执行路径时不经意地将清理代码嵌套在某种条件块中,则无论如何都会存在这种风险,直到结束.我认为最好的办法是让代码更简单、更容易遵循,以避免这种风险.我认为现代语言中可用的编码结构(例如使用"和尝试/最终")也极大地帮助了风险.我现在尝试总是将它们用于清理任务,而不是简单地将代码放在块的末尾.
I don't worry about the risk much because that risk kind of exists anyway if you inadvertently nest the clean-up code inside a conditional block of some sort as you try to manage the various paths of execution retaining the return value until the end. I think the best bet is to keep the code simpler and easier to follow to avoid that kind of risk. I think that risk is also significantly helped by the coding structures available in modern languages such as "Using" and "Try/Finally". I try to always use those for clean-up tasks now instead of simply putting the code at the end of the block.
但是,当其他代码无论如何都想将挂起的返回值作为变量访问时(例如,将其添加到缓存中,以便下次可以更快地返回结果),我确实做了一个例外.
I do make an exception, however, when other code wants to access the pending return value as a variable anyway (to add it to a cache for example, so that the result can be returned more quickly next time).
这篇关于将结果存储在临时变量中而不是多个返回点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!