massmind - Get Together - Watching your code execute

Skip to navigation

Get Connected on
Massmind Logo
Massmind is Powered by Your Contributions.

When I was a younger (and more foolish programmer) I was fortunate enough to learn from some talented software developers. One of the many important lessons I learned was the benefits of watching your code excute. Now, to some, that may sound as exciting as watching the grass grow. But it actually is very interesting and helps you create higher quality code faster.

I know that many people run their code and if it looks like it works they figure - Great, I'm done! But while seeing that it performs as expected is one test of your code, seeing your code in action gives you a much better sense of what's happening and whether it's going to do the right in every case.

Let's take a look at a contrived example in code. I'll use PHP since its what I'm using for most of my work these days, and I'll simplify the code so it's clear what's going on.

function getItemFromDBOrCache()
	$fInCache = false;

	$fINCache = foundInCache($row);

	if (!$fInCache) {	
		$row = fetchFromDB();

	return $row;

If you run this code, your program should work fine. Yes, the cache isn't used, but if you don't have an easy way of checking that, you'll never notice the uppercase typo on the $fINCache line. But, if you set a breakpoint on this function and step through each line, you're very likely to notice the problem (even if there are several lines between the pieces of code in the example). You'd see the cache return the item and then the code still fetch the item from the database. Doing a good code review would probably also uncover this problem, but usually that's later in the development process. I suggest stepping through all new code when you write it.

Or take this example from some recent code I wrote (again, simplified to make the key points obvious).

	if (!findItemToUpdate()) {
		if ($fOutputInfo) {
			echo 'Unable to find objekt for update';
		} else {

I wrote this code and ran it initially without stepping through it in the debugger. I couldn't understand why I didn't get the error message and yet my update still didn't happen. When I looked at the code, the updateItem() function had an obvious bug which I fixed. Thankfully I then ran it while stepping through each line in the debugger and noticed that my else clause was on the wrong if statement (we don't want to update when we're not outputting information, we want to update if we find the item to update). Otherwise I'd have run the code again and still be scratching my head.

A good debugger is critical (I'm surprised at the number of PHP programmers who don't have a debugger in their toolset. I'll talk about my PHP Debugger in a future post). Not only can it help you write better code, but it can make you more efficient (something I'll talk about more in a future post as well).