Coding tip for if statements

When I was a young engineer, a more senior colleague of mine taught me a lot about writing code and helped me adopt my own style. Just like an artist, every developer has his own style with no style being wrong. However, there is one coding convention that he taught me I think all developers should use. Here’s what developers shouldn’t do:

if (something)
       dosomething;

Instead they should do:

if (something)
{
      dosomething;
}

(or if you prefer, put the { on the if line).

Why do I say is? It’s simple, if you come along later and add a line to the first statement, like:

if (something)
        dosomething;
        dosomethingelse;

you could have the wrong thing happen. If you wanted the “dosomethingelse” to only happen if the if statement was executed, that’s not what would happen (it would always execute). The brackets make it explicit what will happen on the if statement. I’ve seen this type of coding in a lot of code and it will definitely lead to failure at some point or another.

I’m sure some people will take offensive with what I say, but this tip will save lots of time in debugging at some point.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.