Skip to content
Advertisement

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement