格式化具有多个条件的if语句的最佳方法

84 language-agnostic if-statement

如果你想根据两个或多个条件执行某些代码,这是格式化if语句的最佳方法?

第一个例子: -

if(ConditionOne && ConditionTwo && ConditionThree)
{
   Code to execute
}
Run Code Online (Sandbox Code Playgroud)

第二个例子: -

if(ConditionOne)
{
   if(ConditionTwo )
   {
     if(ConditionThree)
     {
       Code to execute
     }
   }
}
Run Code Online (Sandbox Code Playgroud)

这是最容易理解和阅读的,记住每个条件可能是一个长函数名称或其他东西.

Eoi*_*ell 126

我更喜欢选项A.

bool a, b, c;

if( a && b && c )
{
   //This is neat & readable
}
Run Code Online (Sandbox Code Playgroud)

如果你确实有特别长的变量/方法条件,你可以直接断开它们

if( VeryLongConditionMethod(a) &&
    VeryLongConditionMethod(b) &&
    VeryLongConditionMethod(c))
{
   //This is still readable
}
Run Code Online (Sandbox Code Playgroud)

如果它们更复杂,那么我会考虑在if语句之外单独执行条件方法

bool aa = FirstVeryLongConditionMethod(a) && SecondVeryLongConditionMethod(a);
bool bb = FirstVeryLongConditionMethod(b) && SecondVeryLongConditionMethod(b);
bool cc = FirstVeryLongConditionMethod(c) && SecondVeryLongConditionMethod(c);

if( aa && bb && cc)
{
   //This is again neat & readable
   //although you probably need to sanity check your method names ;)
}
Run Code Online (Sandbox Code Playgroud)

恕我直言选项'B'的唯一原因是如果您有else针对每个条件运行的单独函数.

例如

if( a )
{
    if( b )
    {
    }
    else
    {
        //Do Something Else B
    }
}
else
{
   //Do Something Else A
}
Run Code Online (Sandbox Code Playgroud)

  • 在第二个例子中,你不是没有理由评估一切吗? (2认同)

Tor*_*ørn 28

其他答案解释了为什么第一种选择通常是最好的.但是如果你有多个条件,可以考虑创建一个单独的函数(或属性)来执行选项1中的条件检查.这使代码更容易阅读,至少在使用好的方法名时.

if(MyChecksAreOk()) { Code to execute }

...

private bool MyChecksAreOk()
{ 
    return ConditionOne && ConditionTwo && ConditionThree;
}
Run Code Online (Sandbox Code Playgroud)

条件只依赖于局部范围变量,您可以使新函数静态并传递您需要的所有内容.如果有混合,传入当地的东西.

  • 我发现这是最有效和更容易添加条件的 (2认同)

Dav*_*ria 10

第一个例子更"易于阅读".

实际上,在我看来,只要你必须添加一些"其他逻辑",你应该只使用第二个,但对于一个简单的条件,使用第一个风格.如果你担心条件很长,你总是可以使用下一个语法:

if(ConditionOneThatIsTooLongAndProbablyWillUseAlmostOneLine
                 && ConditionTwoThatIsLongAsWell
                 && ConditionThreeThatAlsoIsLong) { 
     //Code to execute 
}
Run Code Online (Sandbox Code Playgroud)

祝好运!


int*_*tar 9

问题被提出并且到目前为止已得到回答,好像决定应该纯粹基于"句法"理由.

我会说你如何在if中布置一些条件的正确答案,也应该依赖于"语义".因此,条件应该根据"概念上"的内容进行分解和分组.

如果两个测试真的是同一枚硬币的两面,例如.if(x> 0)&&(x <= 100)然后将它们放在同一行上.如果另一个条件在概念上远远更远,例如.user.hasPermission(Admin())然后把它放在它自己的行上

例如.

if user.hasPermission(Admin()) {
   if (x >= 0) && (x < 100) {
      // do something
   }
}
Run Code Online (Sandbox Code Playgroud)


小智 7

    if (   ( single conditional expression A )
        && ( single conditional expression B )
        && ( single conditional expression C )
       )
    {
       opAllABC();
    }
    else
    {
       opNoneABC();
    }

Formatting a multiple conditional expressions in an if-else statement this way:
1) allows for enhanced readability:
    a) all binary logical operations {&&, ||} in the expression shown
       first
    b) both conditional operands of each binary operation are obvious
       because they align vertically
    c) nested logical expressions operations are made obvious using
       indentation, just like nesting statements inside clause
2) requires explicit parenthesis (not rely on operator precedence rules)
    a) this avoids a common static analysis errors
3) allows for easier debugging
    a) disable individual single conditional tests with just a //
    b) set a break point just before or after any individual test
    c) e.g. ...

    // disable any single conditional test with just a pre-pended '//'
    // set a break point before any individual test
    // syntax '(1 &&' and '(0 ||' usually never creates any real code
    if (   1
        && ( single conditional expression A )
        && ( single conditional expression B )
        && (   0
            || ( single conditional expression C )
            || ( single conditional expression D )
           )
       )
    {
       ... ;
    }

    else
    {
       ... ;
    }
Run Code Online (Sandbox Code Playgroud)

  • 这是我的方法。我唯一的问题是我还没有找到提供此选项的代码美化器 (3认同)

RB.*_*RB. 3

第一个更容易,因为如果你从左到右阅读它,你会得到:“如果某事AND某事ELSE AND某事ELSE THEN”,这是一个很容易理解的句子。第二个例子是“如果有的话那么如果有其他的话那么如果有其他的话那么”,这是笨拙的。

另外,考虑一下您是否想在子句中使用一些 OR - 在第二种风格中您将如何做到这一点?