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?
I have seen so many third party code with silly issues, that I prefer to use braces all the time. That said I have never felt good on
I use if(){} on the same line when it is a short instruction and it is alone. If there is an else use the long:
Those are two lines long, so not really a single line.
There's nothing wrong with single line
if
s when it makes the code easier to read.For example, something like this:
is much better than
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:
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:
In this example, the other programmer added
code C
, but forgot to wrap the wholeelse
block in braces. This will cause problems. You can defend against this by simply wrapping yourif
andelse
blocks in braces.This is something that I actually remember from an employment exam a while back. The code was similar to the following:
Most people here can spot the error, but you can really substitute in anything you want as the "bad code" that was inserted. The more subtle error comes when you have an "old version" of something commented out, and somebody un-comments it, and suddenly the second statement is outside the block.
Basically, unless it's a small test application to learn a concept fast, I always bracket (and even in the test apps I usually bracket). It just isn't worth the headache later if I don't, even in 5-line-methods.
This is more coding style than anything else. That said, my personal opinion is that your second example is potentially quite harmful. It's easy enough to accidentally "add a second line to the block" in languages where braces are the only way to create blocks. But in PHP, where an alternate syntax exists, this is even less likely to set off the necessary warning bells:
Rule of thumb: if you're going to put your "do something" on a separate line, use braces; if you're not going to use braces, put it on the same line!
The problem I've seen is developers not recognizing the {}-less-if when they add code to one of the conditions. Example:
Obviously, this won't do what they expect.