Coding style 早期返回vs嵌套的肯定if语句

Coding style 早期返回vs嵌套的肯定if语句,coding-style,Coding Style,下面是一些假设的代码示例: if (e.KeyCode == Keys.Enter) { if (this.CurrentElement == null) { return false;} if (this.CurrentElement == this.MasterElement) { return false;} if (!Validator.Exist (this.CurrentElement)) { return

下面是一些假设的代码示例:

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
有时更具可读性:

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

我想我会这样写:

if (this.CurrentElement == null OR this.CurrentElement == this.MasterElement OR ...) return false;

第一个例子在各方面都更好。它更简单,更容易阅读。有人说每个函数都应该有一个返回点;这个例子清楚地说明了为什么这些人是错的

就我个人而言,我会删除所有多余的花括号:

if (this.CurrentElement == null) return false;

等等。这使得它更简单,更容易阅读。

我认为第一个更易于阅读和维护。然而,我可能会这样写

if (e.KeyCode == Keys.Enter) {
    if(this.CurrentElement == null ||
       this.CurrentElement == this.MasterElement ||
       !validator.exists(this.CurrentElement) ||
       !identifier.isPictureElement(this.CurrentElement))
    {
        return false;
    {
    else
    {
        this.flattenObjects(this.CurrentElement);
    }
}

假设在第二个示例中,“false”是所有路径的返回,但它是隐式的,而不是声明的,那么为什么不让所有返回隐式为false,并简单地测试唯一的一个条件呢

这可能违反了某人的风格指南,但逻辑上是最简洁的

if( e.KeyCode == Keys.Enter 
 && this.CurrentElement != null 
 && this.CurrentElement != this.MasterElement  
 && Validator.Exist (this.CurrentElement)                     
 && Identifier.IsPictureElement (this.CurrentElement)) 
    this.FlattenObjects(this.CurrentElement);

这是我见过的最糟糕的括号样式之一。呵呵,我真的看到了一些这样的代码。但很抱歉,我这么匆忙地把它打出来,加上适当的括号会更好。这两种做法都不好。我也会这么做,但要有多行,而且语法正确。谢谢,但当我这样做时,行有时会变得很长,假设有6个检查。你可以跨多行。@斯拉克人不知道它是什么语言,所以我如何添加正确/或错误的语法,因为这是一个假设性的问题:PNow你激起了我的好奇心。这是什么?谢谢,这是很有趣的风格。但是你会如何用4-5级嵌套来格式化它,这意味着4-5次检查,对吗?那么上面的方法,你会重构它吗,把它分解成不同的方法吗?@Joan:这完全取决于代码。但是,您可能需要创建一个单独的方法来执行所有验证,并返回
true
false
。谢谢,明白了。只是有时候,你会遇到这些非常独立的独特情况,需要大量的检查,但不能轻松地组合成更少的方法,但我明白你的意思。谢谢,但类、方法不是应该是PascalCase吗?我假设Java,验证器/标识符是对象。好的,我明白你的意思。是的,我总是在C#/.NET模式下思考,但这种技术当然仍然有效。我认为大多数人对单次进入/单次退出的想法是错误的-参见
if( e.KeyCode == Keys.Enter 
 && this.CurrentElement != null 
 && this.CurrentElement != this.MasterElement  
 && Validator.Exist (this.CurrentElement)                     
 && Identifier.IsPictureElement (this.CurrentElement)) 
    this.FlattenObjects(this.CurrentElement);