Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

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

I was told that the first instance wasn't a good idea. I have no idea whether this is really this case (or for the second one either); does it not shorten the amount to type? Or is it because it just makes a mess?

like image 279
unrelativity Avatar asked Mar 27 '09 21:03

unrelativity


1 Answers

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.

like image 70
Ron DeVera Avatar answered Nov 15 '22 19:11

Ron DeVera