9/07/2005

Pre-bug - Variable Notation

A prebug, is a piece of code that is about to become a bug.

This is much like Martin Fowler's code smells (http://www.martinfowler.com/books.html#refactoring) but his writing comes from the perspective of how to find and recognize bad code and refactor it to improve it. The pre-bug concept is more like patterns for defensive coding strategies.

I coined the phrase prebug to describe code that you are typing in that will very soon be re-classified as a bug. Hopefully the test turns your prebug into a bug by failing but what if you can work out a way to type in your code that will prevent you from entering pre-bugs in the first place.

For example, one of the old C bugs that was so common was the single-equal-if problem.


if (a = 1) { printf("I think its one but who really knows"); }

For those unfamiliar with C, this statement would assign 1 to a and return true, always.

As a developer is typing in this code they may not be considering the possible bugs they are generating. So what if we retrained ourselves to always type this.

if (1 = a) { printf(("I know its one"); }

In this case the compiler will thrown an error saying that you can not assign a to the constant 1. What we have done here is slightly change the way we type in code and avoided a nasty bug from passing on down the development stream, potentially to production.

Here is another prebug idea that I want you to suggest solutions for. How would you enter this code to reduce the likelihood of the bug getting passed your ever vigilant eyes?

class Counter extends Thread
{
private static int counter = 0;
public void run()
{
while (counter < 10)
{
counter++;
doSomething();
}
}
}

The bug is that the counter is static and is able to run inside a thread, clealey a problem in this case. The same problem can occur with any static variable even its not so obviously in a class intended for multi-threaded operation.

The best solution I have found for spotting this kind of bug as I am entering it is to classify the variable names by scope and lifetime. We have all seem these notations in coding standards docs for years but I think the application of these ideas for the specific purpose of preventing bugs is not so commonly realized.

The java prefixes I use for these problems are:

statics: s_
instance: m_
arguments: a_

With the statics, instance and argument variables clearly identify to the reading eye what the scope of the variables are. The previous code should be entered like this.

class Counter extends Thread
{
private static int s_counter = 0;
public void run()
{
while (s_counter < 10)
{
s_counter++;
doSomething();
}
}
}

Eclipse offers auto-prefixing so all of its code generation features work once you have configured these notations.