IF ELSE 编码风格 VS IF 编码风格

IF ELSE coding style VS IF coding style

我一直在参考我新公司的代码,我发现代码没有包含在 IF 和 ELSE 周围,所以在流程上有点混乱。例如:

if(user_is_registered)
  {
      // You are already registered.
      //exit
  }
//New user's registration code goes here

而我的上一家公司走的是另一条路,即:

if(user_is_registered)
   {
      // You are already registered.
   }
else
   {
      //New user's registration code goes here
   }

像每个新生一样,我很困惑,这是出于正当理由应遵循的最佳做法。请赐教。我试图找出相同的答案,但找不到。那里有一些答案,其中一些专家支持方式 1,一些专家支持方式 2。如果可用,还请建议我其他参考。谢谢。

如果您希望仅当 if 语句中的条件失败时才执行代码块,则将代码块添加为 if 语句的 else 部分。这些陈述是排他性的。仅执行 if 块或 else 块,而不是两者都执行。

如果您希望代码块始终执行,请在 if 语句之后包含该代码块。该块始终执行。

当您使用 else 时,您正在构建非常明确的逻辑。通过使用单独的 if 语句,您可以在给定条件下应用多个规则块。

可能是被比较的对象满足多个要求,所以Else就不好

举个例子:

    var x = 10;

    if (x < 11){
        // do something
        // - this gets hit
    }else{
        // do something else
    }

    // perhaps i want to have multiple conditions that x meets..
    if (x < 11){
       // do something
        // - this gets hit
    }

    if {x == 10){
      // do something
      // - this gets hit - provided the if before didn't make changes to X
    }

    if (x != 10){
       // do something - this won't be hit, unless a previous if made changes to x
    }

现在 - 当您举出您的特定示例时,如果没有退出方法的方法,您的第一个块中的 //New user's registration code goes here 将始终触发,就像您的 if 中那样.在您的第二个块中,它仅在 if 不匹配时才会触发。

就我个人而言,在这种情况下,我会包含在 if/else 中,并明确代码和意图。

这很可能是为了避免嵌套而做出的决定。在您的示例中,它不是很明显,但是如果在注册逻辑中还有进一步的 IFLOOP 等语句,那么嵌套就会开始发生。

作为一般规则,应该避免并重构嵌套,因为它会妨碍理解,并且通常表明该方法做得太多。

例如

if ( user_is_registered )
{
    // do something & return
}
else
{
   // do something else

   if ( some_other_condition )
   {
      // do another thing

      while (something_is_not_true)
      {
        // loopy things
      }
   }
}