是否有充分的理由说明在函数中只有一个return语句是一个更好的实践?
或者在逻辑上正确的情况下,可以从函数中返回,这意味着函数中可能有许多返回语句?
是否有充分的理由说明在函数中只有一个return语句是一个更好的实践?
或者在逻辑上正确的情况下,可以从函数中返回,这意味着函数中可能有许多返回语句?
当前回答
我更喜欢一个return语句。一个尚未指出的原因是,一些重构工具在单点退出时工作得更好,例如Eclipse JDT提取/内联方法。
其他回答
我经常在一个方法的开头有几个语句来返回“简单”的情况。例如,这个:
public void DoStuff(Foo foo)
{
if (foo != null)
{
...
}
}
... (恕我直言)可以像这样变得更具可读性:
public void DoStuff(Foo foo)
{
if (foo == null) return;
...
}
所以,是的,我认为从一个函数/方法中有多个“出口点”是很好的。
我相信多次返回通常是好的(在我用c#编写的代码中)。单返回样式是从C语言中保留下来的,但是您可能没有用C语言编写代码。
在所有编程语言中,没有法律要求一个方法只有一个退出点。有些人坚持这种风格的优越性,有时他们把它提升为“规则”或“法律”,但这种信念没有任何证据或研究支持。
在C代码中,多个返回样式可能是一个坏习惯,资源必须显式地去分配,但Java、c#、Python或JavaScript等语言具有自动垃圾收集和try. finally块(以及在c#中使用块)等构造,并且这个参数不适用-在这些语言中,需要集中的手动资源回收是非常罕见的。
在某些情况下,单个返回值可读性更好,而在某些情况下则不是这样。看看它是否减少了代码行数,使逻辑更清晰,或减少了大括号、缩进或临时变量的数量。
因此,根据你的艺术感受使用尽可能多的返回,因为这是一个布局和可读性问题,而不是技术问题。
我在我的博客上详细地讨论过这个问题。
Well, maybe I'm one of the few people here old enough to remember one of the big reasons why "only one return statement" was pushed so hard. It's so the compiler can emit more efficient code. For each function call, the compiler typically pushes some registers on the stack to preserve their values. This way, the function can use those registers for temporary storage. When the function returns, those saved registers have to be popped off the stack and back into the registers. That's one POP (or MOV -(SP),Rn) instruction per register. If you have a bunch of return statements, then either each one has to pop all the registers (which makes the compiled code bigger) or the compiler has to keep track of which registers might have been modified and only pop those (decreasing code size, but increasing compilation time).
今天仍然坚持使用一个return语句的一个原因是易于自动重构。如果您的IDE支持方法提取重构(选择一系列行并将它们转换为一个方法),那么如果您想提取的行中有一个return语句,特别是如果您正在返回一个值,则很难做到这一点。
这可能是一个不寻常的观点,但我认为任何相信多个return语句是有利的人都从未在只支持4个硬件断点的微处理器上使用过调试器。:-)
虽然“箭头代码”的问题是完全正确的,但当使用多个return语句时,一个问题似乎消失了,那就是在使用调试器的情况下。您没有一个方便的万能位置来放置断点,以保证您将看到退出,从而看到返回条件。
I've seen it in coding standards for C++ that were a hang-over from C, as if you don't have RAII or other automatic memory management then you have to clean up for each return, which either means cut-and-paste of the clean-up or a goto (logically the same as 'finally' in managed languages), both of which are considered bad form. If your practices are to use smart pointers and collections in C++ or another automatic memory system, then there isn't a strong reason for it, and it become all about readability, and more of a judgement call.