一个函数只有一个返回语句? [英] Should a function have only one return statement?

查看:106
本文介绍了一个函数只有一个返回语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么好的理由为什么在函数中只有一个返回语句是更好的做法?

Are there good reasons why it's a better practice to have only one return statement in a function?

或者从函数返回是否可以在逻辑正确的情况下返回,这意味着函数中可能有很多返回语句?

Or is it okay to return from a function as soon as it is logically correct to do so, meaning there may be many return statements in the function?

推荐答案

我经常有几个语句在一个方法的开始返回容易的情况。例如:

I often have several statements at the start of a method to return for "easy" situations. For example, this:

public void DoStuff(Foo foo)
{
    if (foo != null)
    {
        ...
    }
}

...可以更易读(IMHO)如下:

... can be made more readable (IMHO) like this:

public void DoStuff(Foo foo)
{
    if (foo == null) return;

    ...
}

从函数/方法中获得多个退出点是很好的。

So yes, I think it's fine to have multiple "exit points" from a function/method.

这篇关于一个函数只有一个返回语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆