早期回报率与嵌套正数if语句 [英] Early returns vs nested positive if statements

查看:262
本文介绍了早期回报率与嵌套正数if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是一些假设的代码示例:

  if(e.KeyCode == Keys.Enter)
{
if(this.CurrentElement == null){
return false;}

if(this.CurrentElement == this.MasterElement){
return false;}

if(!Validator.Exist(this.CurrentElement)){
return false;}

if(!Identifier.IsPictureElement(this.CurrentElement)){
return false;}

this.FlattenObjects(this.CurrentElement);
}

VS

  if(e.KeyCode == Keys.Enter)
{
if(this.CurrentElement!= null){

if .CurrentElement!= this.MasterElement){

if(Validator.Exist(this.CurrentElement)){

if(Identifier.IsPictureElement(this.CurrentElement)){

this.FlattenObjects(this.CurrentElement);}}}}}}

}

您认为哪一个在可读性,维护等方面更好?



另外,第二个示例可以通过

解决方案

早期回报更容易阅读。



一个 if

/ code>与 || 子句有时可以更易读:

  if(this.CurrentElement == null 
|| this.CurrentElement == this.MasterElement
|| !Validator.Exist(this.CurrentElement)
|| !Identifier.IsPictureElement(this.CurrentElement))
return false;


Here is some hypothetical code sample:

if (e.KeyCode == Keys.Enter)
{
    if (this.CurrentElement == null) {
        return false;}

    if (this.CurrentElement == this.MasterElement) {
        return false;}

    if (!Validator.Exist (this.CurrentElement)) {
        return false;}

    if (!Identifier.IsPictureElement (this.CurrentElement)) {
        return false;}

    this.FlattenObjects(this.CurrentElement);
}

VS

if (e.KeyCode == Keys.Enter)
{
    if (this.CurrentElement != null) {

        if (this.CurrentElement != this.MasterElement) {

            if (Validator.Exist (this.CurrentElement)) {

                if (Identifier.IsPictureElement (this.CurrentElement)) {

                    this.FlattenObjects(this.CurrentElement);}}}}}}

}

Which one do you think is better in terms of readability, maintenance, etc?

Also the 2nd example can be formatted differently via the different use of parenthesis.

解决方案

Early returns are much more readable.

Whenever you get more than four or five levels of nesting inside a method, it's time to refactor that method.

A single if with an || clause can sometimes be more readable:

if (this.CurrentElement == null
 || this.CurrentElement == this.MasterElement
 || !Validator.Exist(this.CurrentElement)
 || !Identifier.IsPictureElement(this.CurrentElement))
    return false;

这篇关于早期回报率与嵌套正数if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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