Skip to Navigation or
Skip to Content

Always Use Those Curly Braces

Feeds

RSS Feed

<< April | May | June >>

Tuesday, 4th May 2010

I write a lot of code in a lot of different languages - but there is one common rule I apply to all of them... when you use an "if" block, always put in the curly braces even if you don't need them. I have now lost count of the number of times I have seen an error that is related to this simple style rule.

To illustrate, let's look at the "wrong" way of doing things. I'll pop the example in JavaScript - but this applies equally to many other languages such as C#, VB, PHP and so on.

if (something == 10)
    alert("Something equals 10");

In this example, if the variable "something" is equal to 10, an alert will pop up to tell you so. If it doesn't equal 10, no alert will pop up. This is all well and good until the code is modified. For example, there is a requirement to reset something to 0 when it gets to 10. This leads to the following common error:

if (something == 10)
    alert("Something equals 10");
    something = 0;

In this example, the alert will only pop up if something equals 10, but the line of code to reset something to 0 will happen every single time, no matter what the value of something is. All of this can be avoided by using curly braces in the first place - it seems like such a trivial and obvious problem, yet I keep on encountering this error, either in code or in questions asked on various help forums.

if (something == 10) {
    alert("Something equals 10");
}

This example leaves us in no doubt whatsoever about what is included in the if statement and what isn't. It doesn't matter that it is a one liner - this is the most readable and maintainable state for the code to be in.

Of course, this doesn't stop at curly braces - the same error happens all the time in HTML because people aren't in the habit of laying out their nested tags properly. It isn't OCD to layout your code neatly, it is fundamental to the readability of your code. I'll finish with the updated second bit of code, which properly resets something to 0 when it equals 10.

if (something == 10) {
    alert("Something equals 10");
    something = 0;
}

 

You Are Here: Home » Blog » Always Use Those Curly Braces


I use a cookie on this website. This cookie doesn't contain or relate to any personal information and it isn't shared with any other website, it just ensures that I don't count you more than once in my website statistics. The Privacy and Electronic Communications Regulations require me to ask your permission to use this cookie, so please indicate below that you are happy for me to do this - I will remember your selection with a cookie, so if you accept I won't ask again...