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 *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the answer to the math equation shown in the picture. Click on the picture to hear an audio file of the equation.
Click to hear an audio file of the anti-spam equation