单次/单次出入境规则 [英] Single-entry/single-exit rule

查看:70
本文介绍了单次/单次出入境规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某处读了一条规则:

I have read a rule somewhere to:

遵循单次进入/单次退出规则.永远不要在同一个函数中编写多个return语句.

Follow the single-entry/single-exit rule. Never write multiple return statements in the same function.

这句话是真的吗?如果是这样,您能否详细说明为什么我们应该遵守该规则?

Is this statement true? If that so, could you please give more detail as to why we should follow this rule?

推荐答案

我个人不反对提早退房,但我将提议考虑SingerOfTheFall的第三种替代方案.

I'm personally not opposed to early-exit, but I'll propose a third alternative to SingerOfTheFall for consideration.

优势:

  • 正常代码流(即无错误)清晰地流经代码
  • 没有机会失败一个东西"并通过另一个某物"无意中执行了一段代码
  • 您可以在代码块上强制作用域;包括在范围的出口处清理代码子块中使用的内容

缺点:

  • 缩进可能会加起来(尽管可以通过断开来减轻这种情况进入子功能)
  • 在编辑器中没有大括号匹配的情况,可能很难将错误与失败的条件匹配

int foo()
{
    int errorCode = 0;
    if(!something) {
        //100 lines of code
        if(!something) {
            //100 lines of code
            if(!something) {
                //100 lines of code
            }
            else {
                errorCode = -1;
            }
        }
        else {
            errorCode = 11;
       }
    }
    else {
        errorCode = 1;
    }
    return errorCode;
}

这篇关于单次/单次出入境规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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