SAF(NET) = STEPHEN A. FUQUA operating on the Web since 1995

Stephen is a web developer, Bahá'í, and interfaith activist in St. Paul, Minnesota. He likes to write about religion, social justice, sustainability, science, programming, &c.

January 12, 2009

The value of using braces to avoid code defects

Something I was reading this weekend pointed out that leaving braces out of a one-line block can be dangerous. For instance, it is correct to code the following (and I do it all the time!)

                if (someCondition)
                                this.doSomething();

There are two different ways this can be problematic. Let’s give a little more context. Perhaps the code has this:

                if (someCondition)
                                this.doSomething();
                                this.doAnotherThing();

Now, if the programmer had let Visual Studio control the tabs properly, then this would be more clear:

                if (someCondition)
                                this.doSomething();
                this.doAnotherThing();

We can’t necessarily count on this tabbing though. So when someone new comes in and looks at the code, what are the chances that this person will think that this.doAnotherThing() is being called in the if block? I don’t know the percentage, but it is probably too high. The other side of the confusion comes in when a programmer decides to augment the original if block with a call to doAnotherThing() (for example). Perhaps that programmer wasn’t paying enough attention, and didn’t notice that there are no braces. Then in this example we would have a real problem – doAnotherThing() is being called all the time, when it should only be called as part of the condition!

After thinking about these issues, I am resolving to not take the lazy step that I’ve always liked and preferred – that is, to no longer leave out curly braces when the block statement has only one line. This will also been seen with many using statements.

TrackBack

Comments

Post a comment

Remember personal info?




deprecated

On safnet.com

Other sites managed or developed by S.A.F.

S.A.F. elsewhere on the web

  • LinkedIn
    LinkedIn can actually be useful when looking for prospective hires and business or organizational partners
  • GoodReads
    A fun and relatively-unknown social networking site geared towards one's book list
  • Live Journal
    Mirror of the blog at safnet.com, so that a few LJ friends can more easily read and comment there