There’s a truism of programming that the earlier you find a bug, the easier it will be to fix. That’s generally true…but I think it’s even more true to say that the later you find a bug, the more of a pain in the ass it will be to fix.
Once a bug exists, people will unintentionally write code that relies on that bug. Sometimes that shaky bit of bug-reliant code is nearby, in the same system as the bug. Sometimes it’s not nearby—maybe it’s downstream, in a bit of code that calls your system and depends on the incorrect results your bug causes. Or it’s upstream—a chunk of code that only works because the bug caused you to call it in a particular way.
This is a natural thing—it’s impossible to avoid. We notice things that go wrong, not things that go right. When things go wrong, we investigate to figure out why. But when things don’t go wrong, we don’t investigate. If your code works, or at least seems to work, then there’s a natural tendency to assume that it works in the way you think it works, when very often it works for reasons you’ve never imagined. And since you don’t investigate, you never discover the tangled set of circumstances that led to your code accidentally working.
That’s true for the code you write, and it’s true for the code other people write that calls your code. When you commit a bug to your team’s codebase, the codebase will slowly but inevitably accumulate other bits of code that rely on your bug. These hidden entanglements only become visible when you fix an obvious bug and some other part of your project mysteriously stops working.
The sooner you find the bug, the fewer of these entanglements will have time to sprout. That means fewer dependencies to clean up—which is often the most time-consuming part of fixing a bug. It’s painfully common to spend more time dealing with the repercussions of a bug fix than fixing the bug itself.
It’s useful to think of bugs as being contagious. Each bug in your system tends to create new bugs, as new code works around the bug or relies on its incorrect behavior. The best way to stop the resulting contagion is to eliminate bugs as early as possible, before their evil influence can spread.
Don’t Count on Your Users
OK, so we want to detect problems early. How do we do that?
Here’s one thing you can’t count on—your users. Whether that means teammates calling your code or customers exercising your feature, users aren’t a great first line of defense. Sure, sometimes they’ll report a problem, but more often they’ll assume the behavior they’re observing is the behavior you intended. That’s where the entanglements come from—unnoticed issues, sure, but also issues that are noticed but then assumed to be part of the design.
You can try to ameliorate this. You can write better user-facing documentation. You can drag your team into a meeting room to explain a new system or feature. You can maintain an up-to-date internal wiki with details about how everything fits together, or put a tech note on your support site. All of these things are worthwhile—they all help, albeit at nontrivial expense and with varying levels of effectiveness—but they don’t solve the problem. Fundamentally, your users don’t understand your intent as well as you do, so they’re going to assume bugs are features no matter what you do.
A better answer is some sort of continuous automated testing. Most programmers would agree that automated testing is a Good Thing. At a minimum, programmers think that automated testing is a Good Thing for other programmers to do, whether or not they can be bothered to do it themselves.
There are lots of homegrown variations on the idea of continuous automated testing, as well as more formalized methodologies like test-driven development .
Generally speaking, the idea is that your system (or better yet, your whole project) has a set of tests that you can run quickly and conveniently and that thoroughly 1 exercise the system (or project) and report problems. If the tests are truly quick and convenient, they’ll get run all the time—like every time you compile or run the project. Any bugs that pop up that early are easy to nip in the bud. If the tests are only theoretically quick and convenient, they’ll tend to get run as part of the commit process—which is still early enough to avoid the entanglement growth that makes bugs hard to fix .
This sort of testing is expensive. Writing the tests for some bit of code can take as much time as writing the code itself. Advocates of automated testing, however, would argue (convincingly!) that this is an illusion. After all, the hidden cost of writing that bit of code is detecting and diagnosing problems later, when they’re hard to fix. Coding is debugging, right? Testing proponents argue that it’s faster to test up front—perhaps even, if you’re a diehard, writing a test before you write the code it intends to test.
Continuous automated testing isn’t something you can easily adopt as a personal practice. Making it work requires investing in quite a bit of infrastructure—you’ll need a nonintrusive testing framework, a testing-friendly deployment system, and a team that’s philosophically committed to automated testing. Unless the whole team buys in, you’re swimming against the tide. But if you’re on a team that buys in, great!
Despite the obvious value in a test-centric approach, we haven’t committed to it at Sucker Punch. We do have automated tests for many systems, but collectively they cover only a small part of our codebase. Why is that ?
Automated Testing Can Be Tricky
Some projects and some problems lend themselves better to automated testing than others.
Some things are hard to test, either because it’s hard to cover all possible inputs or because it’s hard to validate the outputs. Imagine you’re writing a new lossy audio compression codec. How do you write an automated test for it?
It’s easy to verify that your compressor doesn’t crash, or to measure how much compression you see against some set of test files. It’s not as easy to verify that the decompressed audio actually sounds like the original. You’re writing an audio compression codec, so you probably have enough signal processing math to write tests that flag obvious problems, but at some point you’ll need to slap headphones on human ears and ask people to pick the compressed sample out of three options. That’s not a test you can run quickly or conveniently.
Some code is inherently hard to test because its success is hard to measure—and a lot of the code that gets written at Sucker Punch qualifies. Does a shopkeeper character act like a real shopkeeper would? Does that facial animation actually convey disgust, or does the character just look they’re about to burp? Does it feel like I’m firing a bow here, even though I’m really holding a controller?
If you’re working on a project that has big chunks of difficult-to-test code, then you’re forced into a hybrid model. Test what you can test, control what you can control, and remember that you’re not testing everything. Any areas that aren’t covered by your automated tests will need to be tested manually: plan accordingly.
That said, you can structure your code to make it easier to test.
Imagine you’re going to write an external automated test for some bit of code—that is, some bit of testing code, separate from the code you’re writing, that will call your code with a set of inputs designed to flex its capabilities, then check that the outputs match expectations. How can you structure your code to make this test easier to write ?
Stateless Code Is Easier to Test
One important strategy is to reduce the amount of state in your code. It’s a lot easier to test code that doesn’t rely on state. Any pure function—a bit of code that relies only on its direct inputs, has no side effects, and has predictable results—is easy to test. Better this :
int sumVector(const vector<int> & values)
{
int sum = 0;
for (int value : values)
{
sum += value;
}
return sum;
}
Than this:
int reduce(
int initialValue,
int (*reduceFunction)(int, int),
const vector<int> & values)
{
int reducedValue = initialValue;
for (int value : values)
{
reducedValue = reduceFunction(reducedValue, value);
}
return reducedValue;
}
To test sumVector , you just need a set of inputs and the expected outputs for those inputs. That’s exactly the sort of thing that test-driven development frameworks excel at. If there’s state involved, the set of inputs required to thoroughly exercise the code gets a lot more complicated.
Testing reduce is harder—in the apparent pursuit of generality, or maybe as a half-step toward threading, it repeatedly calls a passed-in function on the values in vector . You can certainly use reduce to sum the values in the vector:
int sum(int value, int otherValue)
{
return value + otherValue;
}
int vectorSum = reduce(0, sum, values);
But testing reduce presents problems. Who knows what the reduceFunction function is going to do, right? Does it rely on some bit of external state? What happens if it has side effects? What if calling that function removes something from the values vector you’re iterating over? If you’re testing reduce , you’ve got to anticipate and test all of those things. That’s a much more complicated set of tests than you’d need for sumVector .
To thoroughly test code, you need to present it with a thorough representation of all the states it might encounter, then evaluate its outputs against those states. With a pure function, the arguments to the function are the only state that matters. But when you bring in side effects, internal state, or callouts to arbitrary functions, the amount of state that might matter explodes. This forces a compromise—you can accept less thorough test coverage, or write an unmanageable number of test cases .
Let’s look at a simple example. Imagine you’re tracking a prioritized list of characters. Each character has a priority, and it’s easy to get a list of all characters sorted by that priority. The interface is simple:
class Character
{
public:
Character(int priority);
~Character();
void setPriority(int priority);
int getPriority() const;
static const vector<Character *> & getAllCharacters();
protected:
int m_priority;
int m_index;
static vector<Character *> s_allCharacters;
};
It’s not hard to keep s_allCharacters sorted, with all characters in priority order. You could do this incrementally, tracking where each character lives in your prioritized list and being careful to scoot it back and forth in the list only minimally when its priority changes. That means inserting the character in the right place when it’s created:
Character::Character(int priority) :
m_priority(priority),
m_index(0)
{
int index = 0;
for (; index < s_allCharacters.size(); ++index)
{
if (priority <= s_allCharacters[index]->m_priority)
break;
}
s_allCharacters.insert(s_allCharacters.begin() + index, this);
for (; index < s_allCharacters.size(); ++index)
{
s_allCharacters[index]->m_index = index;
}
}
Cleaning up indexes when the character is destroyed:
Character::~Character()
{
s_allCharacters.erase(s_allCharacters.begin() + m_index);
for (; index < s_allCharacters.size(); ++index)
{
s_allCharacters[index]->m_index = index;
}
}
And scooting the character back and forth in the list by a minimal amount if its priority changes:
void Character::setPriority(int priority)
{
if (priority == m_priority)
return;
m_priority = priority;
while (m_index > 0)
{
Character * character = s_allCharacters[m_index - 1];
if (character->m_priority <= priority)
break;
s_allCharacters[m_index] = character;
character->m_index = m_index;
--m_index;
}
while (m_index + 1 < s_allCharacters.size())
{
Character * character = s_allCharacters[m_index + 1];
if (character->m_priority >= priority)
break;
s_allCharacters[m_index] = character;
character->m_index = m_index;
++m_index;
}
s_allCharacters[m_index] = this;
}
This works, but testing it is complicated. There’s hidden state that an external test can’t get at. A test that creates a set of prioritized characters then checks that allCharacters returns them in the proper order will catch some bugs, but it will miss some too. The current index could be screwed up even if the characters are in the right order, and there’s no way to check that using the methods Character exposes. Incorrect indexes might cause problems, but there’s no guarantee those problems will show up soon (or even ever). And with three separate code paths, each trying to keep the indexes correct, it’s easy to slip up.
It’s simpler to test a stateless version of Character , one that doesn’t try to maintain state:
class Character
{
public:
Character(int priority) :
m_priority(priority)
{
s_allCharacters.push_back(this);
}
~Character()
{
auto iter = find(
s_allCharacters.begin(),
s_allCharacters.end(),
this);
s_allCharacters.erase(iter);
}
void setPriority(int priority)
{
m_priority = priority;
}
int getPriority() const
{
return m_priority;
}
static int sortByPriority(
Character * left,
Character * right)
{
return left->m_priority < right->m_priority;
}
static vector<Character *> getAllCharacters()
{
vector<Character *> sortedCharacters = s_allCharacters;
sort(
sortedCharacters.begin(),
sortedCharacters.end(),
sortByPriority);
return sortedCharacters;
}
protected:
int m_priority;
static vector<Character *> s_allCharacters;
};
There’s still state here, since you’re tracking all the characters in s_allCharacters , but it’s not hidden. Writing the test for this version of the code might not be as simple as writing the tests for a pure function, but it’s a lot simpler than writing the tests for the incremental version of Character you started with.
With the prior state-based approach, you had to be paranoid about what order you did things in. Minus that state, you can just check for expected outputs and feel pretty safe .
This sort of stateless code is easier to get right in the first place, too. That’s a hidden advantage of test-driven development—code that’s easier to test tends to be easier to write. If you’re thinking about how you’re going to test some bit of code you’re about to write, you’ll end up writing something simpler .
Audit State You Can’t Eliminate
Let’s say that circumstances force you into keeping some state. Maybe the call pattern encourages it—say your sorted list of characters sees minor priority adjustments interleaved with calls to AllCharacters , and all of the sorting in your stateless implementation is thrashing your memory caches.
If it’s hard to write an external test because you can’t get at some bit of internal state, write an internal test instead. 2 An easy way to do this is to have an auditing method on your data—in this case, an audit function that checks whether the internal state is consistent:
void Character::audit()
{
assert(s_allCharacters[m_index] == this);
}
This is a pretty short audit function, but that’s because I’ve stripped out anything interesting from this Character class to use it as an example. A real Character class would be likely to have more internal state and a longer audit function.
You can also audit the consistency of your array:
void Character::auditAll()
{
for (int index = 0; index < s_allCharacters.size(); ++index)
{
Character * character = s_allCharacters[index];
if (index > 0)
{
Character * prevCharacter = s_allCharacters[index - 1];
assert(character->m_priority >= prevCharacter->m_priority);
}
character->audit();
}
}
There are advantages to this sort of internal testing, especially if you think of internal tests as a complement to external tests. Often you can leave internal tests running all the time, which means they’re running on actual real-world test cases, not the artificial ones you built for your unit test.
Someone has to call these internal functions for them to be useful, obviously! A good rule of thumb is calling Character::audit at the end of any method that updates the character’s state, and calling Character::auditAll whenever the list changes. You can dial audit frequency up and down based on need .
Don’t Trust the Caller
In the normal course of programming, you’re going to write code that gets called by other people on your team. Even if you only work on one-person projects, some future version of you will call your code—and that future version of you might as well be a stranger. Future You won’t remember the details, and other callers never knew them. So don’t trust that the caller is going to get the details right!
The caller will pass incompatible sets of arguments. They’ll neglect to call expected initialization functions, and they’ll forget to call shutdown functions. They’ll provide a callback function that doesn’t actually fulfill the basic requirements expected of that function. They’ll get it all wrong…and if you don’t detect the mistakes, they won’t get fixed. An entanglement will grow instead—this time not from a bug in your code, but from a bug in the calling code.
It might be counterintuitive, but the easiest place to find those bugs isn’t in the calling code, it’s in the code being called. The caller might be making the mistakes, but you’re in a better position to catch them.
Now, with good design, you can often make it impossible for callers to get the details wrong. That’s the subject of Rule 7, “Eliminate Failure Cases” . Sometimes you can’t, though. What do you do in those cases?
Here’s an example. You’re writing a rigid-body physics simulator that’s going to be used by three different video games under development at your company. You’ll be tracking internal state, like which rigid bodies are in contact with each other, and that state has to get stored somewhere. You can’t just call operator new , though, like you would in standard C++ code. Memory is tight, and your clients have their own custom memory managers you need to integrate with.
There’s a straightforward answer—have your clients hand over functions to allocate and free the memory you need as part of an initialization step. I’m tempted to start with a few bad examples of how to do initialization, but I’ll skip to a decent one instead. If you’re actually writing a rigid-body physics simulator, you’re likely to have more initialization parameters than the two named in the following code snippet. The gravitational constant, for instance. Collect all of the initialization parameters into a single structure, which is then passed to a single initialization function :
struct RigidBodySimulator
{
struct InitializationParameters
{
void * (* m_allocationFunction)(size_t size);
void (* m_freeFunction)(void * memory);
float m_gravity;
};
void initialize(const InitializationParameters & params);
void shutDown();
};
Expose methods to add and remove new simulated rigid bodies to the system, and to get and set their current state :
struct RigidBodySimulator
{
struct ObjectDefinition
{
float m_mass;
Matrix<3, 3> m_momentOfInertia;
vector<Triangle> m_triangles;
};
struct ObjectState
{
Point m_position;
Quaternion m_orientation;
Vector m_velocity;
Vector m_angularVelocity;
};
ObjectID createObject(
const ObjectDefinition & objectDefinition,
const ObjectState & objectState);
void destroyObject(
ObjectID objectID);
ObjectState getObjectState(
ObjectID objectID) const;
void setObjectState(
ObjectID objectID,
const ObjectState & objectState);
};
The expected usage pattern is pretty obvious, right? Initialize the simulator before you use it, and shut it down when you’re done. Add objects, manipulate them, destroy them when you’re done. Nothing complicated.
But you can’t trust the caller to get even the simple details right. They’ll forget to call initialize , they’ll ask for object state on objects that have been deleted, or they’ll try to set object state on a random ObjectID that you’ve never handed out .
It’s tempting to just ignore these cases—to assume that people will get the details right and let the chips fall where they may—but that’s a huge mistake. If you don’t detect the error and report it somehow, things will end in tears. Either callers won’t notice their mistake, or they’ll assume the observed behavior is a feature.
Imagine you’ve implemented ObjectID as a wrapper around a smaller integer, which is then used as an index into a linear list of ObjectState structures:
struct RigidBodySimulator
{
struct ObjectID
{
int m_index;
};
ObjectState getObjectState(
ObjectID objectID) const
{
return m_objectStates[objectID.m_index];
}
void setObjectState(
ObjectID objectID,
const ObjectState & objectState)
{
m_objectStates[objectID.m_index] = objectState;
}
vector<ObjectState> m_objectStates;
};
This design is simple and easily understood, but it’s is pretty shaky. It lets easy-to-make mistakes by the caller go unnoticed. Try to get an object’s state after you destroy it and the results will be undefined.
Actually, that’s a little misleading, though it’s the way people usually talk about interfaces like this. They mean “undefined” in the sense that the interface doesn’t promise any particular result when you call getObjectState for a destroyed object—but, in practice, the results are completely defined! In the implementation (which I’m not showing you), if you call getObjectState immediately after destroying that object with destroyObject , you get the state the object had right before it was deleted. It would be easy to assume, implicitly or explicitly, that this was the intended behavior…and from such assumptions do entanglements grow. 3
Undefined results are the mark of a poorly designed interface.
Don’t let this incorrect usage go unremarked. Anyone calling getObjectState after destroyObject should hear about it—but first you need to detect the problem. One easy fix is to supplement the index in ObjectID with a “generation” number:
struct RigidBodySimulator
{
class ObjectID
{
friend struct RigidBodySimulator;
public:
ObjectID() :
m_index(-1), m_generation(-1)
{ ; }
protected:
ObjectID(int index, int generation) :
m_index(index), m_generation(generation)
{ ; }
int m_index;
int m_generation;
};
bool isObjectIDValid(const ObjectID objectID) const
{
return objectID.m_index >= 0 &&
objectID.m_index < m_indexGenerations.size() &&
m_indexGenerations[objectID.m_index] == objectID.m_generation;
}
ObjectID createObject(
const ObjectDefinition & objectDefinition,
const ObjectState & objectState)
{
int index = findUnusedIndex();
++m_indexGenerations[index];
m_objectDefinitions[index] = objectDefinition;
m_objectStates[index] = objectState;
return ObjectID(index, m_indexGenerations[index]);
}
void destroyObject(ObjectID objectID)
{
assert(isObjectIDValid(objectID));
++m_indexGenerations[objectID.m_index];
}
ObjectState getObjectState(ObjectID objectID) const
{
assert(isObjectIDValid(objectID));
return m_objectStates[objectID.m_index];
}
void setObjectState(
ObjectID objectID,
const ObjectState & objectState)
{
assert(isObjectIDValid(objectID));
m_objectStates[objectID.m_index] = objectState;
}
vector<int> m_indexGenerations;
vector<ObjectDefinition> m_objectDefinitions;
vector<ObjectState> m_objectStates;
};
The generation detects incorrect usage of object IDs. When you create or destroy an object, you bump its generation version number. If you try to destroy an object, then get its state, the generations won’t match and this mismatch will be reported. 4 The caller is notified that they’ve made a mistake and can correct it before it has a chance to fester.
You could easily add code that checks for the other usage mistakes I’ve identified—forgetting to call initialize , for instance. Or calling it twice. In the preceding code the interface is redesigned a bit to make it harder to create invalid object IDs—the only public constructor creates a valid object ID, so the caller only has easy access to object IDs that are properly constructed and returned .
There’s a reasonable discussion to be had about how to flag usage errors like this—you could use asserts, but you could just as easily return error codes or throw exceptions. Your answer will depend on your team’s conventions. The important thing is that you flag the error, not how you do the flagging .
Keeping Your Code Healthy
Code that’s easier to test—or, better yet, continually tests itself—stays healthier longer. It’s best to think about this from the start, before you write your first line of code for some new part of the project. You might start with writing an automated test, as with test-driven development. You might opt for a stateless implementation of the functionality, or add continual internal auditing of the functioning of the code.
The result is contagious bugs being discovered early, before they have chance to multiply. That means fewer problems to fix, and easier fixes to make when fixes are necessary.
And there’s a hidden benefit! Most of the techniques that make code easier to test also make the code easier to write—having to write tests for all use cases nudges you to simplify to fewer use cases. Eliminating state makes for less fiddly code. Making your interfaces less error-prone makes them simpler .
It’s a two-way win. So keep things simple, and keep on testing.
1 …although perhaps not completely. I won’t weigh in on what percentage of your codebase you should aim for covering with automated tests. Keep reading; our percentage at Sucker Punch is very low.
2 You could also expose the internal state to your testing code somehow—weakening encapsulation by “friending” your test code, say. It’s more maintainable in my experience to add internal tests instead.
3 This is also a hole in many automated tests, which rarely test unspecified cases as thoroughly as they do specified ones. Your automated tests are unlikely to detect this destroyObject + getObjectState example.
4 One of the standard paradigms for reporting problems in C is the assert macro. One way or the other, it pops up a message at runtime if the condition it’s passed is false . The message varies depending on which compiler and operating system you’re using (!), but typically it includes the line number in the source code where the assert failed and the expression passed to the assert.