Thursday, October 23, 2008

Mmmm, Beer!




What would you rather do - drink beer, or fight cancer? Soon, you may be able to do both at the same time. Woohoo!

Friday, October 10, 2008

What's With All The Flag Waving?

OK, time for a soapbox sermon. I've had a few blog post ideas swirling around for a while now, but this one really got me going...

Flag variables.

I can't tell you how many times I've seen code like:
flag1 = false;
flag2 = true;
flag1 = SomeFunctionThatReturnsTrueOrFalse();
if (flag1 == true)
{
flag2 = false;
}
if (flag2 == true)
{
flag3 = SomeOtherFunctionThatReturnsTrueOrFalse();
}
if (flag3 == true)
{
// do something
}
Oh, I wish I could tell you that the code above is something I totally made up just to make a point. Sadly, it's not. The above is real code with the function names and specific syntax changed to protect the not-so-innocent.

If a flag variable is assigned, tested in a following line, and never used again, I cringe! It makes the code harder to follow and debug and also wastes CPU and memory. True, creating one boolean variable and then assigning a value isn't an overly expensive process, but it is a waste and is the type of thing that can build up and bite you somewhere unpleasant in a multi-user app and/or large code base.

What about a good compiler, you say? Sure, some compilers are pretty good about optimizations. Most will probably drop the redundant boolean comparison from the condition, and some might even do away with the flag altogether. But that's only in the executble, the mess is still in your source code to cause confusion.

However, not all code is compiled! Does FireFox's JavaScript implementation make this kind of optimization? IE's? Opera's? Webkit's? What about the numerous other interpreted languages?

I consider flag variables to be only a small step away from GOTO statements. Like GOTOs, they might have a time and place, but should be used judiciously, if at all. Like GOTOs, they are often overused and abused.

If you set, test and never use it again, get rid of that darn flag. If a number of different conditions can possibly set the flag and then it is used later on to make a decision, maybe you need it, but you can probably still code better.

Yes, I have used flags (and GOTOs) in the past. Would you believe me if I said it was only back when I was 7 years old, first learning to program in BASIC on a TRS-80? Probably not.

But far too many programmers just are not disciplined enough and modern hardware makes it easy to get away with poor code. Considering the advances in hardware, shouldn't Word 2007 on a dual-core make Word 2.0 on a 386 look dog-slow? Sure, you hit a point of diminishing returns when trying to over-optimize code, but if some fairly basic discipline was more prevalent, Vista would have been a huge success for Microsoft because there would never be a wait dialog and everyone would be thrilled with how fast and efficient it was.