Curly brackets usage in the case of single line statements is a matter of style and personal preference, but my humble recommendation - especially for people new to coding - would be to use them regardless of how many statements follow your if/else/while/whatever, because this clearly shows at first glance which code is intended for execution.
For example: Let's say I have a block which looks like this:
Code: Select all
if (ship == player)
doSomethingWithPlayer();
Let's assume that I want to add a line that outputs a log statement before doSomethingWithPlayer for debugging reasons. One of the common mistakes a green coder would do is this:
Code: Select all
if (ship == player)
log("I am doing something with the player ship");
doSomethingWithPlayer();
Now we have just introduced a bug in the code. If ship equals player, then a log line will be written and then the doSomethingWithPlayer will be executed regardless of the if statement above, because it is considered an independent statement. The way it is indented, doSomethingWithPlayer looks as if it belongs to the if statement, but it really doesn't. One needs to remember to enter the curly brackets here.
If this had been written as
Code: Select all
if (ship == player)
{
doSomethingWithPlayer();
}
from the beginning, then we can add the new log line in the block without worrying about the case described above. We'll just do a
Code: Select all
if (ship == player)
{
log("I am doing something with the player ship");
doSomethingWithPlayer();
}
and everything will work as expected. If the ship equals player, then both the log line and the doSomethingWithPlayer will be executed and if ship does not equal player then none of the two will be executed.
Hope this helps.