If I tell you that coding is really debugging , you’ll probably shake your head ruefully and mutter something along the lines of “Ain’t it the truth, buddy. Ain’t it the truth.”
Well, not really—nobody talks like that. But you’d certainly agree with the premise. When you’re turning an idea into a fully working implementation, you’ll inevitably spend a lot more time in the “getting it to work” phase than in the “typing it in” phase. Barring extreme circumstances—a simple idea and a run of incredible luck, say—you’ll spend more time debugging than coding. This is so obvious it’s rarely even stated.
Here’s the twist.
You know that coding is actually debugging, but how does that affect the way you approach coding projects? You know that coding is actually debugging—so what are you going to do about it?
One obvious answer is to write code with fewer bugs. That’s what the rest of this book is about, so let’s set it aside for now. This Rule is about something different: writing code that’s easy to debug.
The Lifecycle of a Bug
Let’s take a step back and think about what debugging actually is. There are four basic stages in the lifecycle of a bug:
-
The bug is detected—you discover the problem.
-
Next it’s diagnosed—you investigate and uncover what’s causing the errant behavior.
-
Then you fix it, changing your implementation to eliminate the errant behavior.
-
Finally, you test to make sure that the bug has actually been fixed and that your fix didn’t cause new problems, then you commit the fix.
The diagnosis phase is often the longest and most frustrating. That’s because most bugs arrive with no details. Typically you’ve got a description of the symptom—the program crashed, or the OK button on a dialog is always disabled, or a list of all your users swaps the first and last names for a quarter of the entries. If you’re lucky, the bug report will have some context, such as what the user was doing when the program crashed.
What you’re missing is why the symptom occurred. What led to the symptom? What exactly went wrong? Diagnosis is the process of answering these questions. Until you know what went wrong, you can’t fix the problem.
The thing you’ve got going for you is that computers are deterministic. If the computer is presented with exactly the same situation, it will generate exactly the same result. If you don’t see the same result, then you didn’t reproduce the situation exactly.
Bugs would be easy to diagnose if you could time travel back to right before things started going wrong. Then your job would be easy—just step through the code looking for trouble. If you accidentally step past the problem, or if you didn’t start early enough, no worries: fire up your time machine and pop a little further backward in time.
Of course, you can’t actually time travel—or, if you can, you’ll have higher priorities for your time travel powers than fixing bugs in your code. Instead, you need to fake the ability to time travel, getting the code back into exactly the situation that will cause the problem, then break into the debugger right before things go sideways.
There’s often a gap between things starting to go sideways and the bug’s symptom showing up, so knowing when to break into the debugger is a bit of a magic trick. If you’re really lucky, the actual underlying problem and the symptom are one and the same:
void showObjectDetails(const Character * character)
{
trace(
"character %s [%s] %s",
(character) ? character->name() : "",
character,
(character->sourceFile()) ? character->sourceFile() : "");
}
A crash here with a null object is easy to diagnose. The symptom (the crash) is in the same statement as the actual problem (we’re checking whether character is null, implying that null objects are supported, but then dereferencing character with no null check two lines later). With no gap between symptom and problem, diagnosis is easy.
Or, at some slightly smaller value of “lucky,” the symptom and problem are neighbors:
int calculateHighestCharacterPriority()
{
Character * bestCharacter = nullptr;
for (Character * character : g_allCharacters)
{
if (!bestCharacter ||
character->priority() > bestCharacter->priority())
{
bestCharacter = character;
}
}
return bestCharacter->priority();
}
Another null pointer crash, this time if calculateHighestCharacterPriority is called when no characters exist. The symptom here (crashing with bestCharacter still null) is separated by a few lines from the problem (the logic of the preceding loop doesn’t handle an empty characters list).
Here we get the first inkling of the actual process of diagnosing a bug. Earlier we said that if we could time travel back to the point where things started going wrong, it would be easy to diagnose the bug. That’s true, and that’s sort of what we’re doing during diagnosis, but it’s rare to be able to jump all the way back to the original cause, the point where things started going wrong, all in one step.
It’s more typical for things to fall apart bit by bit instead of all at once. Instead of jumping straight back in time to the point where things go wrong, you’re working backward bit by bit. You identify something that looks wrong, then work backward to identify when it started looking wrong. That often leads to something else that looks wrong, another process of working backward, then more rounds of the same until you land on the pebble whose tumble started the whole avalanche that led to your eventual symptom. That’s what diagnosing a bug is.
I understand if this effort to decompose the process of debugging doesn’t seem useful. You started with an idea of what debugging is like. You’re a programmer, and coding is debugging, so you’ve debugged code. Why all this effort to describe a process that’s obvious?
Well, our goal is to make debugging easier, and we can’t do that without a crisp definition of what debugging is.
If we define debugging as the process of stepping backward in time, reconstructing the cascade of things going wrong that eventually lead to the symptom we’ve detected, then we make debugging easier by making it easier to step backward in time. Eventually, we work backward to the pebble that started the avalanche, which is where we’d like to fix things. The easier it is to work backward, the more likely we are to follow the chain of causation to its source.
That’s the thing about avalanches. We don’t have to work all the way backward to the original pebble. We can just fix the symptom, and not worry about diagnosing our way backward to the cause of that symptom. Faced with the crash in our second example, we could just add a null pointer check to stomp on the symptom, the crash when called with no characters:
int calculateHighestCharacterPriority()
{
Character * bestCharacter = nullptr;
for (Character * character : g_allCharacters)
{
if (!bestCharacter ||
character->priority() > bestCharacter->priority())
{
bestCharacter = character;
}
}
return (bestCharacter) ? bestCharacter->priority() : 0;
}
When working backward is hard, there’s a strong temptation to do exactly this—to fix the symptom rather than tracing back to its cause. The temptation is strong because in some sense it works. This code was crashing, and now it’s not. Your work is done.
If we’d done just a little bit more tracing backward, we’d probably realize that a better fix would be getting rid of the bestCharacter pointer:
int calculateHighestCharacterPriority()
{
int highestPriority = 0;
for (Character * character : g_allCharacters)
{
highestPriority = max(
highestPriority,
character->priority());
}
return highestPriority;
}
Most bugs aren’t as simple as this example. Patching the symptom without tracing backward to the original problem leaves that original problem still lying in wait, poised to start an avalanche.
In this example, the pebble is a pointer that’s null, but only in a special case. We wrote code that missed the special case once. We’re likely to miss that special case again. Better to get rid of the pebble by eliminating the pointer entirely.
The temptation to deal with the symptom rather than its cause exists at every step along the way of your exploration up the causal chain. As you slowly work your way backward in time from symptom to cause, and to the cause of that cause, and then the cause of that cause, at any point you can stomp on a problem and declare victory. This is a victory of sorts—the eventual symptom that prompted your debugging disappears.
But declaring victory midway through the avalanche means that the pebble is still there. At some point it will cause another avalanche, whether you’re the coder who gets buried or someone else is. The easier we make it to take steps backward in time, the easier it is to resist the temptation to fix symptoms instead of tracing back to their root causes . That makes it easier to fix pebbles instead of patching avalanches. 1
Minimizing State
Given this definition of debugging, we can spot the opportunities for improvement:
Pushing symptoms closer to causes makes tracing upstream easier.
If the cause is nearby in the source code, or if it happened more recently, then discovering the connection gets easier.
Reducing the length of the causal chain shortens the debugging process.
A symptom that has a single cause is easier to fix than a symptom with a long cascade of symptoms leading to causes leading to other causes ad nauseum.
Making it easier to hop backward in time helps trace each link.
If it’s easy to reproduce the state that led to the cause of each symptom, it will be easy to explore the causal chain.
The easiest target here is the last one listed. Reproducing state is hard if there’s lots of state. If we reduce the amount of state we need to reproduce, we’ll have an easier time hopping backward up the causal chain.
It’s easy to debug a problem in a pure function—a function that has no side effects and depends only on its inputs. If the function returns an incorrect value for some set of inputs, just call it again with the same inputs and it will return the same output. Repeat as needed.
Say we’re calculating Fibonacci numbers, and we’ve got a bug. Calculating Fibonacci numbers is a problem that is only ever solved in programming tests and whiteboard interviews, but hang with me. Here’s the code. 2 The bug report is that getFibonacci returns the wrong value:
int getFibonacci(int n)
{
static vector<int> values = { 0, 1, 1, 2, 3, 5, 8, 13, 23, 34, 55 };
for (int i = values.size(); i <= n; ++i)
{
values.push_back(values[i - 2] + values[i - 1]);
}
return values[n];
}
This is a pure function, so reproducing the problem is easy. The only state it relies on is its argument, so every time we call getFibonacci(8) we’ll get the same incorrect result, 23 instead of 21. Once we’re stepping into the function, it’s pretty obvious what’s wrong—we’re priming the values array with the wrong value. Diagnosis complete.
That’s our first takeaway, then. If you build your code with pure functions, you’ll have an easier time reproducing state and an easier time debugging problems.
Let’s look at a more complicated scenario. Imagine we’ve got a Character method that returns a “threat” value based on that character’s current weapon, armor, health level, status effects, and so on. We could write code to maintain that threat value as state in the character :
struct Character
{
void setArmor(Armor * armor)
{
m_threat -= m_armor->getThreat();
m_threat += armor->getThreat();
m_armor = armor;
}
void setWeapon(Weapon * weapon)
{
m_threat -= weapon->getThreat();
m_threat += weapon->getThreat();
m_weapon = weapon;
}
void setHitPoint(float hitPoints)
{
m_threat -= getThreatFromHitPoints(m_hitPoints);
m_threat += getThreatFromHitPoints(hitPoints);
m_hitPoints = hitPoints;
}
int getThreat() const
{
return m_threat;
}
protected:
int m_threat;
Armor * m_armor;
Weapon * m_weapon;
float m_hitPoints;
};
There’s a bug in this code, reported as something like “player doesn’t appear threatened by an enemy with a +1 Sword of Grievous Wounding.” Luckily this bug is easy to reproduce manually. If you walk up to the enemy holding the magic sword, the player character still plays his unconcerned animation instead of looking ready for action.
The preceding code isn’t where that symptom shows up, of course. The actual symptom in this case is the player character playing an inappropriate animation, looking unconcerned when they should be looking threatened. We’ve already traced a few steps upstream in the causal chain before we hit our example code, but when we do we find that m_threat doesn’t have the right value.
So now we need to figure out why it doesn’t have the right value! We’ve got to do the magic trick of jumping backward in time, reproducing the state that led to m_threat being set to the wrong value.
And that’s tricky in this case. The code isn’t “nearby,” like it was in the prior simple examples. Nor is it “recent.” At some point in the past, we set m_threat to the wrong value, but we’re not sure when.
That’s the problem with stateful code. You don’t detect problems until long after things have gone sideways, and this delay between cause and symptom makes diagnosing the problem difficult. In this case, we know that m_threat has the wrong value, but we’re not sure why or when that incorrect value was set.
If you follow the advice about audit functions in Rule 2 , then diagnosing the problem is cake. Add a call to the audit function whenever you’re updating the character’s state:
struct Character
{
void setWeapon(Weapon * weapon)
{
m_threat -= weapon->getThreat();
m_threat += weapon->getThreat();
m_weapon = weapon;
audit();
}
void audit() const
{
int expectedThreat = m_armor->getThreat() +
m_weapon->getThreat() +
getThreatFromHitPoints(m_hitPoints);
assert(m_threat == expectedThreat);
}
};
If we do this, then the audit function asserts at the end of setWeapon . Face palm; we meant to subtract the threat from the old weapon before adding the threat from the new weapon. It’s no wonder the player character was so blasé.
Without the help of an audit function, diagnosing the problem is decidedly not cake. You probably end up placing breakpoints on all the lines where m_threat is set, then running the code and verifying the state each time you hit one of those breakpoints. Tedious, and in this case easily avoided—you shouldn’t have been maintaining m_threat as a bit of state. Don’t add state unless it’s absolutely necessary.
Contrast with a similar bug in stateless code:
struct Character
{
void setArmor(Armor * armor)
{
m_armor = armor;
}
void setWeapon(Weapon * weapon)
{
m_weapon = weapon;
}
void setHitPoint(float hitPoints)
{
m_hitPoints = hitPoints;
}
int getThreat() const
{
return m_armor->getThreat() -
m_weapon->getThreat() +
getThreatFromHitPoints(m_hitPoints);
}
protected:
Armor * m_armor;
Weapon * m_weapon;
float m_hitPoints;
};
With the stateless code, we have a clear plan of action when we discover Character::getThreat is returning the wrong value. Walk up to the enemy with the magic sword, then set a breakpoint on getThreat . Diagnosis is easy—there’s an errant minus sign where a plus sign was clearly intended. Reducing the amount of state made diagnosis much easier.
We haven’t eliminated state entirely from Character . The state that remains— the character’s armor, weapon, and current hit points—is sort of the point of the Character object. It’s irreducible .
That’s true for a lot of video game code, where we’re modeling real-world objects with virtual analogs, and those objects have state. Like an object’s position and velocity, or the player’s current hit points, or what magic gems are slotted into the player’s magic sword. That’s all state, and it’s not easily eliminated.
But where you can get rid of state, do. State makes debugging harder, and coding is debugging. Where possible, build behavior out of pure functions. It’s easier to get the details correct, and when things go wrong problems are a lot easier to diagnose .
Dealing with Unavoidable State
When state is unavoidable it makes diagnosing problems more complicated. Imagine you’re diagnosing a problem—characters sometimes react inappropriately to arrow impacts. They’re expected to stumble backward, 3 but sometimes they stumble forward instead.
Hmm. There’s a suggestive word in that bug description…“sometimes” tells you that the problem is probably related to the state of the interacting objects—my guess would be the problem is inside the character, which probably has the most state, though the arrow is also a possibility. Diagnosing the problem is going to require reproducing that state.
That might be easy! If the bug is showing up 100% of the time in one of your unit tests, you’re home free. The unit test is creating the state that leads to the incorrect behavior, which makes diagnosis straightforward. Set a breakpoint that fires when the ill-fated arrow hits the character and start debugging—you might need to explore up the causal stream to find the pebble that started the avalanche, but the hard part of each step backward in time is reproducing state, and the unit test is taking care of that for you.
Or maybe you’re slightly less lucky. You don’t have an automated test, but given a few tries you can reproduce the problem manually, and you can detect the problem when it occurs.
In the Sucker Punch engine there’s an object that maps every damage record to an appropriate reaction—that’s where the code decides what a character does when an arrow thunks into them. We can detect the problem in the mapping code—we just need to add code that makes sure the impact velocity of the arrow and the character stumble direction point in the same direction :
void DamageArbiter::getDamageReaction(
const Damage * damage,
Reaction * reaction) const
{
// All the actual logic for mapping damage to reactions goes here.
// There's a single function that does this in the Sucker Punch
// engine. That function is nearly 3000 lines long and is not the
// purest embodiment of the Rules, though to be fair it's solving
// a very complicated problem.
if (damage->isArrow())
{
assert(reaction->isStumble());
Vector arrowVelocity = damage->impactVelocity();
Vector stumbleDirection = reaction->stumbleDirection();
assert(dotProduct(arrowVelocity, stumbleDirection) > 0.0f);
}
}
When this assert fires, you’re in good shape to diagnose the problem.
The getDamageReaction function is relatively pure—it returns the same Reaction every time for any bit of Damage , and it doesn’t have side effects, but it also makes decisions based on the state of arbitrary objects in the world. That sounds like a disaster—do we have to reproduce the state of every single object in the world in order to reproduce the problem?
That’s why it’s important that we detect the problem early, before we return from getDamageReaction . That lets us diagnose the problem. The function has no side effects, so the state of all the objects in the world hasn’t changed. If we call getDamageReaction again immediately, we should get the same result.
In the olden days I’d insert code to handle this. When the problem is detected, break into the debugger to let me start single-stepping, then call the pure function recursively:
void DamageArbiter::getDamageReaction(
const Damage * damage,
Reaction * reaction) const
{
// All the actual logic for mapping damage to reactions goes here.
// There's a single function that does this in the Sucker Punch
// engine. That function is nearly 3000 lines long and is not the
// purest embodiment of the Rules, though to be fair it's solving
// a very complicated problem.
if (damage->isArrow())
{
assert(reaction->isStumble());
Vector arrowVelocity = damage->impactVelocity();
Vector stumbleDirection = reaction->stumbleDirection();
if (dotProduct(arrowVelocity, stumbleDirection) <= 0.0f)
{
assert(false);
static bool s_debugProblem = CHRISZ;
if (s_debugProblem)
{
getDamageReaction(damage, reaction);
}
}
}
}
These days, I can be more improvisatory. The IDE we use at Sucker Punch lets me set the next line to execute whenever I’m stopped on a line in the debugger. This is not without some danger, since randomly jumping around in the code can create its own problems, but given some care it works well. If I realize I’ve hit a problem, especially in a pure function, I can pop backward in the code to identify the cause of the problem. This ability transforms diagnosis. A single step backward in time that was difficult to execute has become easy. If the underlying cause of the problem is local—recent, and nearby in the code—then it’s easy to find .
Eliminating state doesn’t have to be an all-or-nothing thing. Making some bit of code completely stateless will make it easier to diagnose problems, even if nearby code still maintains state. Every little bit of state you eliminate helps .
Dealing with Unavoidable Delay
In the examples we’ve looked at so far, we could detect the symptom mechanically. If we crashed, then the problem sort of detected itself. If our code is self-policing through asserts, then it detects its own problems. In cases like our arrow example, we noticed the problem through manual testing, but could translate the problem into an assert in the code.
Detecting symptoms like this isn’t always possible, and this complicates diagnosis. Sometimes the symptom isn’t immediately apparent.
Here’s a Sucker Punch example—debugging problems in our animation code. The movement of characters in our games is driven by animations created by our animation team. Each animation describes where each part of the character’s body moves as a function of time. Say, at 1.5 seconds into the animation, the left hand goes exactly here and is oriented exactly like this; at 1.53 seconds into the animation, it’s moved slightly up and rotated forward a tiny bit. And so on, for each of the six hundred or so parts of the character body we manage, every sixtieth of a second as long as the animation lasts.
Each animation on its own is a pure function. It doesn’t rely on any external state, or have any side effects. All it cares about is its sole input variable, the exact time within the animation’s timeline we’re evaluating. If we repeatedly evaluate the animation with the same input variable, we’ll repeatedly get the same body position.
It’s not quite that simple, though. When we switch from one animation to another—when a character who is running decides to jump, say—then we don’t just cut over to the new animation. That would cause the character’s body to pop into a new position, which looks bad. Instead, we smoothly transition from the old animation to the new one.
Smoothing makes things more complicated because it relies on the character’s current body position as well as the position in the animation timeline. For us to reproduce a problem in smoothing, we need the position and orientation of all six hundred or so parts of the character’s body we manage as well as that single timeline value for the animation.
Wait, it gets worse! While our brains are really good at detecting glitches in animations, it takes a while for us to realize we’ve seen a problem, and we’re reevaluating the animation sixty times a second. By the time we realize that something looked wrong, we’ve reevaluated the animation a dozen times, and whatever state caused the animation glitch is long lost.
There’s a solution, though it’s an expensive one. Animation smoothing relies on a lot of state, but at least it’s state we can identify. If we captured all of that state every time we evaluated the animation, then we could reevaluate the animation smoothing using that state to diagnose problems.
And in fact that’s what we do. Because glitch-free animation is an absolute requirement, we’ve invested in debugging animations. We capture all the character state that affects animation every frame, and have a debugging tool that lets us scroll back and forth over recent evaluations of the animation. When we see a glitch, we can pause the game, fire up the animation debugging tool, scroll backward in time to the glitch, then break into the debugger to start tracing from symptom to cause up the causal chain.
With this tool we automated the hard part of debugging—reproducing the state that led to the problem. If you’ve got code that relies on state, but that state can be scoped, then capturing the state makes debugging a lot easier.
Think of this technique as creating an executable logfile—a logfile that doesn’t just describe what happened, but contains all the data necessary to cause that same thing to happen again. If you’ve built your system out of pure functions, then building an executable logfile is completely plausible. You just capture all of the inputs and provide a way to play them back .
This isn’t easy to do, but for crucially important and hard-to-debug problems like animation quality at Sucker Punch, it’s worth the effort.
1 So how do you know when you’ve found the pebble and not just another symptom? Well, if you’re not sure why or when the purported pebble occurs, then you probably haven’t found the pebble and should keep investigating. But don’t obsess about it—every step uphill toward the actual pebble is helpful.
2 This is not a good way to calculate Fibonacci numbers. Don’t use it on a programming test.
3 This is movie logic. Arrows don’t have that much energy. They’re not going to knock anything bigger than a squirrel backward. But it’s what everyone playing video games expects, so there you go.