它是在方法好习惯使用一个以上的RETURN语句? [英] Is it good practice use more that one RETURN statement in a method?

查看:156
本文介绍了它是在方法好习惯使用一个以上的RETURN语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/708675/why-is-it-good-practice-to-return-at-the-end-of-a-method\">Why它是很好的做法在方法年底

返回

我想知道是否可以被认为是一种方法,为什么好习惯使用几个return语句。
如果没有,我想知道你将如何改写code以不同的方式。

 公共字符串GetNominativeById(INT?candidateId)
        {
            如果(candidateId.HasValue)
                返回repepositoryCandidate.GetById(candidateId.Value).Nominative;
             其他
                返回的String.Empty;
            }
        }

通过一个返回

 公共字符串GetNominativeById(INT?candidateId)
    {
        字符串结果;
        如果(candidateId.HasValue)
            结果= repepositoryCandidate.GetById(candidateId.Value).Nominative;
         其他
            结果=的String.Empty;        返回结果;
        }
    }


解决方案

没有,它被认为<击>坏习惯不太好做法有一种方法多个出口。它更容易跟随code,如果有退出的单点。

然而,当该方法是小如在这个例子中,不难跟随code,无论如何,所以有多个出口点是不是一个真正的问题。如果它使code简单,可以很好地使用多个收益语句。

Possible Duplicate:
Why is it good practice to return at the end of a method

I would like to know if could be considered good practice use several RETURN statements in a method and why. If not, I would like to know how you would rewrite the code in a different way.

public string GetNominativeById(int? candidateId)
        {
            if (candidateId.HasValue)
                return repepositoryCandidate.GetById(candidateId.Value).Nominative;
             else
                return string.Empty;
            }
        }

With one RETURN

 public string GetNominativeById(int? candidateId)
    {
        string result;
        if (candidateId.HasValue)
            result =  repepositoryCandidate.GetById(candidateId.Value).Nominative;
         else
            result =  string.Empty;

        return result;
        }
    }

解决方案

No, it's considered bad practice not so good practice to have multiple exit points in a method. It's easier to follow the code if there is a single point of exit.

However, when the method is as small as in the example, it's not hard to follow the code anyway, so having multiple exit points is not really a problem. If it makes the code simpler, you can very well use multiple return statements.

这篇关于它是在方法好习惯使用一个以上的RETURN语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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