Categories
computer

Avoiding if(DEBUG_ON)

Consider the following Java code..

public class Counter {

	private final static boolean DEBUG_ON = false;

	protected int mCount = 0;

	public int getCount() {
		return mCount;
	}

	public void increment() {
		if(DEBUG_ON) {
			System.out.println(“about to increment! count=” + getCount());
		}
		mCount++;
	}
}

}

Some people use “debug” or “test” flags because they can provide a fast way of troubleshooting situations that would otherwise be inconvenient to debug. If increment() was recursive, for example, it may be convenient to simply keep an eye on stdout rather than set breakpoints and have to step through it. (Note: see an earlier post on conditional breakpoints to avoid this entirely.)

While the extra DEBUG_ON code is fairly harmless and benign, it’s nevertheless unnecessary code that could potentially break a production system, and even when/if you do remember to comment it out, it distracts the reader from the meaningful, real code you’re trying to express.

An alternative solution? Simple. Subclass it. Try this instead..

public class Counter {

	protected int mCount = 0;

	public int getCount() {
		return mCount;
	}

	public void increment() {
		System.out.println(“about to increment! count=” + getCount());
		mCount++;
	}

}

public class TestCounter extends Counter{

	public void increment() {
		System.out.println(“about to increment! count=” + getCount());
		super.increment();
	}
}

Now you can leave your print statements intact, and just use TestCounter as a drop-in replacement for Counter in your unit tests. Alternatively, you could use one of many design patterns to aggregate or compose the Counter rather than extend it, or use dynamic proxies or aspects if you’re looking to intercept calls that exist in a horizontal manner.