Are singleline if statements or if statements without braces bad practice?

前端 未结 12 2236
天涯浪人
天涯浪人 2021-01-01 17:10
if (condition) { /* do something */ }
else { /* do something */ }

if (condition)
    /* do something */
else
    /* do something */

I was told tha

12条回答
  •  我在风中等你
    2021-01-01 17:28

    The best practice is to write code that others can read and update easily.

    Your first form is questionable because it doesn't follow the forms that most PHP developers are used to:

    if (condition) {
      // code
    } else {
      // code
    }
    
    // ... or ...
    
    if (condition)
    {
      // code
    }
    else
    {
      // code
    }
    
    // ... or ...
    
    if (condition) { /* short code */ } else { /* short code */ }
    
    // ... or ...
    
    condition ? /* short code */ : /* short code */;
    

    Note that this is entirely about standard practice, and doesn't necessarily make sense—it's only about what other developers are used to seeing.

    Your second form, more importantly, isn't so good because it makes it easy for another programmer to make this mistake:

    if (condition)
      // code A
    else
      // code B
      // code C (added by another programmer)
    

    In this example, the other programmer added code C, but forgot to wrap the whole else block in braces. This will cause problems. You can defend against this by simply wrapping your if and else blocks in braces.

提交回复
热议问题