I end up spending a lot of time looking through code, trying to figure out what it’s doing. The subject might be code I’m trying to debug, some bit of code I’m thinking about calling from some code I’m writing, or some bit of code that’s calling code I’m responsible for. And frequently the thing the code is trying to do isn’t what it’s actually doing , which is what makes the exercise interesting.
At its best, reading code is just like reading any other language. You sail along through the narrative, top to bottom, eagerly following the twists and turns of the plot, and reach the end of the code with a full understanding of what it does and why.
Actually, at its easiest, you sight-read code just like you’d sight-read a single word:
int sum = 0;
Or maybe:
sum = sum + 1;
There’s no thinking or reasoning involved for these two examples—a glance at the code is enough to understand it. You can do the same thing for bigger chunks of code, if they neatly fit some common paradigm:
Color Flower::getColor() const
{
return m_color;
}
You might even be able to sight-read a whole loop:
int sum = 0;
for (int value : values)
{
sum += value;
}
That’s pushing things, though. As blocks of code get bigger, it becomes harder to sight-read them—or if you’re a cynical old programmer like me, it gets harder to trust your ability to sight-read them, having made the mistake of glancing at code and thinking I understood it way too many times.
When code gets too big to sight-read, you start reasoning about it. Think about what your brain is doing when you look at this code:
vector<bool> flags(100, false);
vector<int> results;
for (int value = 2; value < flags.size(); ++value)
{
if (flags[value])
continue;
results.push_back(value);
for (int multiple = value;
multiple < flags.size();
multiple += value)
{
flags[multiple] = true;
}
}
You almost certainly didn’t sight-read this—that is, you didn’t glance at it and immediately think “Sieve of Eratosthenes” . Instead, you read through the code, top to bottom, sight-reading a line or so at a time, reasoning through what each line did and how it fit with the lines that had come before.
Maybe, in detail, your thought process went something like this:
flags is a vector filled with 100 false s.
Looks like we’re going to collect results in this array.
OK, just a loop over the flags array, kind of fun to start a loop index at two, not sure what that’s about.
Hmm, skipping if the flags array is set for the current value, not sure what that’s about either…
Pushing the values we don’t skip into the results array? That must be the output.
Another loop, this time over the multiples of value.
Ah, OK, we’re marking all the multiples, this is the Sieve of Era-whatever…Erathosanes? That’s why we started with two instead of zero or one. I understand this now: the results vector ends up with a list of prime numbers.
The reasoning process involved some mental juggling—seeing something you didn’t quite understand, then setting it aside for a moment until you figured out how it fit together with later code, just like a juggler tosses a ball into the air knowing that they’ll need to catch it a bit later. In this case, you juggled two mysteries—why the loop started at two, and why the outer loop skipped flagged values. The loop over multiples resolved the two mysteries—you caught the juggled balls and understood the code.
Jugglers can only juggle so many balls—three, in my case. The number of balls you can mentally juggle is a bit bigger, but it’s still limited. There’s a surprisingly low limit to how many thoughts you can set aside at once. If you try to track too many, you’ll start losing track of a random subset of the things you’re trying to remember.
That’s because “mental juggling” or “cognitive load” is really just short-term memory. 1 To simplify things, there’s a difference between your long-term memory , the things you remember permanently, and your short-term memory. Think about memorizing a shopping list, which exercises your short-term memory—if there are two or three items on your list, you just remember them. If there are a dozen, you’ll need to write them down.
That’s because there’s a limit to how many things fit in short-term memory. You may have heard the approximation that you can only fit seven (plus or minus two) thoughts into your short-term memory. Try to fit any more, and the new thoughts bump out the old ones. This is just as true when you’re reading code as it is when you’re trying to remember all of the items on your shopping list at the grocery store .
For most of us, that seven (plus or minus two) number is a fairly hard limit. 2 Juggling three separate coding thoughts is easy—it takes no special effort to hold onto a few mysteries about some bit of code you’re reading. Tracking a dozen thoughts, on the other hand, is pretty much impossible. If there are a dozen things you don’t understand about some bit of code, you’re in deep trouble. In programming terms, your cache overflows, and you lose track of some of the things you’re trying to figure out.
This Is What Failure Feels Like
As programmers , we’ve all had the experience of trying and failing to figure out how some bit of complicated code works. You look through the code and see stuff you don’t understand. In an attempt to understand it, you pop elsewhere in the code, searching for the function that gets called, or the structures that are defined, or looking for some comment that at least gives some context. And that search leads to another search. By the time you actually figure something out about the code, you’ve lost track of where you were to begin with. You’re forgetting things at approximately the same rate you’re learning things. Frustrating!
The Role of Short-Term Memory
Good code doesn’t set its reader up for this sort of failure. Code gets written once but read many times, after all; if you want to write good code, you need to think about the person reading it later. Don’t ask that person to juggle too many new ideas at once.
If some bit of code forces the reader to keep more than seven (plus or minus two) balls in the air, then balls will get dropped. And everything the reader is trying to fit into their short-term memory counts as a ball. It’s not just unresolved mysteries, though those obviously count. It’s also the accumulated facts and connections they’re managing, hoping to see connections to the unresolved mysteries. If the total count of mysteries and facts and connections goes above your reader’s limit, then things will get dropped.
Those drops make the code hard to read. If the reader drops some fact that’s necessary to solve a mystery, then that mystery won’t get solved. And neither you nor the reader has control over which thought gets dropped—so the one fact key to unraveling the mystery goes missing, and the mystery isn’t resolved.
Let’s count the amount of running thoughts required for the code example:
vector<bool> flags(100, false);
vector<int> results;
for (int value = 2; value < flags.size(); ++value)
{
if (flags[value])
continue;
results.push_back(value);
for (int multiple = value;
multiple < flags.size();
multiple += value)
{
flags[multiple] = true;
}
}
flags is a vector of 100 bools, all false to begin with (+1). Count = 1.
The result looks like the output of the loop (+1). Count = 2.
It’s a loop with index value starting at two (+1). Count = 3.
We’re skipping values for some reason (+1). Count = 4.
Ah, OK, we’re storing the values into results . Theory confirmed (+0). Count = 4.
Another loop, this time over multiples of value (+1). Count = 5.
Everything collapses down to “the results vector is full of primes.” Count = 1.
The thought count stays safely below the limit, even if we’re counting thoughts conservatively, so there’s no danger of overflowing the reader’s ability to keep track of things. And the count doesn’t just go up—it can also go down. When a variable goes out of scope, say, there’s no point in worrying about it anymore. Or, more importantly, when a whole collection of ideas collapses into a single thought.
In this example, that happened when you realized that the code generates a list of prime numbers. You were juggling a bunch of details about the code, then realized how they fit together. Once you knew how they fit together, you stopped worrying about the details and just held onto the result. All the details collapsed into a single thought.
Good code makes this process easy. It’s collapsible. It stays within the limits of short-term memory. It presents its ideas in small, related chunks, with each chunk carefully written to fit inside the reader’s short-term memory, be put together, then collapse down to a single thought .
There are some easy techniques for doing exactly that. Let’s look at a longer example:
void factorValue(
int unfactoredValue,
vector<int> * factors)
{
// Clear flags marking multiples of primes
vector<bool> isMultiple;
for (int value = 0; value < 100; ++value)
isMultiple.push_back(false);
// Find primes by skipping multiples of primes
vector<int> primes;
for (int value = 2; value < isMultiple.size(); ++value)
{
if (isMultiple[value])
continue;
primes.push_back(value);
for (int multiple = value;
multiple < isMultiple.size();
multiple += value)
{
isMultiple[multiple] = true;
}
}
// Find prime factors of value
int remainder = unfactoredValue;
for (int prime : primes)
{
while (remainder % prime == 0)
{
factors->push_back(prime);
remainder /= prime;
}
}
}
The middle section of this function is exactly the same logic as the last example—but this version is much easier to understand. 3 That’s because it’s more collapsible.
Good names help immensely. The names primes and isMultiple give you a head start on collapsing the loop—it’s no surprise that the array ends up containing prime numbers. You might have spotted the Sieve of Eratosthenes a lot earlier if the array in the first example had been named primes —that’s the power of a good name.
The name primes is also a mighty convenient handle for the idea that the array does in fact hold prime numbers. If the variable had been named xx instead, you’d have needed to burn a precious short-term memory slot remembering that xx is an array of primes. Remembering that primes contains primes is trivial. At worst, it pushes your short-term memory budget toward seven plus two, instead of seven minus two; at best, it’s so self-explanatory that it’s free, placing zero burden on your short-term memory.
The comments also collapse the details, since they tell you what each chunk of code is trying to do. And the comments have a second function—they mark the chunks for you. Between each pair of comments there’s a chunky little code puzzle, small enough to fit inside your short-term memory, which collapses down to a single thought. The comment at the start of each chunk tells you what that chunk is going to collapse to. Reading the code in the chunk just confirms the comment.
This is the power of abstraction. It’s how you manage to understand complicated things. Sure, you can only remember seven (plus or minus two) new things at a time, but you can aggregate those things into new concepts, then build things out of those aggregated concepts. Instead of remembering all the details, you remember the abstraction—and remembering a simple abstraction only soaks up one of your short-term memory slots .
Where to Draw the Line
Marking the abstractions with function boundaries can also help readability. In this case, that might mean splitting the three commented sections of getFactors into separate functions:
void clearFlags(
int count,
vector<bool> * flags)
{
flags->clear();
for (int value = 0; value < count; ++value)
flags->push_back(false);
}
void getPrimes(
vector<bool> & isMultiple,
vector<int> * primes)
{
for (int value = 2; value < isMultiple.size(); ++value)
{
if (isMultiple[value])
continue;
primes->push_back(value);
for (int multiple = value;
multiple < isMultiple.size();
multiple += value)
{
isMultiple[multiple] = true;
}
}
}
void getFactors(
int unfactoredValue,
const vector<int> & primes,
vector<int> * factors)
{
int remainder = unfactoredValue;
for (int prime : primes)
{
while (remainder % prime == 0)
{
factors->push_back(prime);
remainder /= prime;
}
}
}
Then factorValue can be rewritten in terms of these three functions:
void factorValue(
int unfactoredValue,
vector<int> * factors)
{
vector<bool> isMultiple;
clearFlags(100, &isMultiple);
vector<int> primes;
getPrimes(isMultiple, &primes);
getFactors(unfactoredValue, primes, factors);
}
Is this easier to read?
Yes and no! The functions define clear concepts, and once you understand what they do, the names help fix the concepts in your head.
But instead of a simple linear progression of code, reading top to bottom, you’re hopping around from function to function. If you start by digging into factorValue , the first thing you run into is a call to clearFlags . You have to find that function and read it to see what it does. While you’re looking at clearFlags , you have to remember where you came from in factorValue , track which variables correspond to which arguments, then put everything back together when you pop out of clearFlags .
So there’s more to track, and that makes it harder to collapse the concepts. Remembering all the contextual details soaks up short-term memory slots, and you’ve only got seven (plus or minus two) slots to work with. Remembering where you are in a nested call chain can overload your short-term memory all by itself.
There’s a thought in programming that abstraction is always a net positive —that anything that can be pulled into a function should be pulled into a function. The more functions, the better. Since abstraction is the tool we use to understand complicated things, it seems to follow that anything that can be abstracted should be abstracted .
The Cost of Abstraction
This is silly. There’s a cost to abstraction, and a cost to separating out logic into functions. This cost can outweigh the benefits. Here’s an example:
int sum = 0;
for (int value : values)
{
sum += value;
}
That’s pretty simple code to understand, if you already know that values is a vector of integers. It collapses easily—loop over the values, add them all up, and you’ve got the sum.
You might see this instead:
int sum = reduce(values, 0, add);
Hmm. This is certainly concise. You might infer from the names of sum and add that it’s calculating some sort of sum, but that’s just a guess. To know for sure, you’d need to start investigating.
To start with, it’s not clear what the reduce function (or at least something that looks like a function) is doing, nor is it clear what add is, and the 0 passed as an argument is a mystery too. Searching for reduce in your codebase produces a lot of hits, but it looks like this is the one that’s important:
template <class T, class D, class F>
D reduce(T & t, D init, F func)
{
return reduce(t.begin(), t.end(), init, func);
}
OK, that’s a start. Looks like the first argument to reduce is a container class, since begin and end are standard bits of C++ iteration goo. You need to find the four-argument version of reduce :
template <class T, class D, class F>
D reduce(T begin, T end, D init, F func)
{
D accum = init;
for (auto iter = begin; iter != end; ++iter)
{
accum = func(accum, *iter);
}
return accum;
}
Things become a little bit clearer! The reduce function loops over a collection, successively applying a function (or function-like thing) to each element and an accumulated value. Popping back out a few levels, you expect that add will add two values, and it does:
int add(int a, int b)
{
return a + b;
}
Now the last pieces click into place. This use of reduce is calculating the sum of the values in the array, just like the simple loop you started with…but the simple loop is much easier to read and understand. It collapsed easily, where this more abstracted version of the algorithm required real effort to collapse. The extra layers of abstraction aren’t helping, they’re just obscuring what’s going on. You had to find and interpret four separate bits of code to understand things, stretching your short-term memory to do so.
Use Abstraction to Make Things Easier to Understand
I think there’s a good rule of thumb hidden here for making abstraction decisions, whether that’s to break logic out as a function, or to use some general-purpose abstraction to solve your specific problem. The rule is simple—will this change make the code simpler and easier to understand? Will the code collapse more easily with the change? If so, create the function or employ the abstraction. If not, don’t .
The Role of Long-Term Memory
This chapter has been pretty bleak so far! A budget of seven (plus or minus two) thoughts in short-term memory is pretty stingy. It’s hard to see how you could build anything even half-complicated with a conceptual budget that small, even if you’re focused on collapsing thoughts into more abstract thoughts at every opportunity.
So that can’t be the whole story! I know for certain that I’m completely familiar with way more than seven (plus or minus two) things in our engine. There are dozens and dozens 4 of methods on the main Sucker Punch character class, and I know what they all do. What’s going on?
Well, it’s simple. All of the details I know about our game tech are stored in my long-term memory, and there’s not a fixed budget for that. I am certain you have quick recall for a truly impressive amount of stuff about your projects—concepts, facts, names, development history, the person to talk to when something goes wrong, funny stories about a bug you had to fix in that one function. All of that lives in your long-term memory.
You use short-term memory to figure stuff out—it’s the working storage for any reasoning you do, the place the pieces hang out while you try to figure out how they fit together. Once the puzzle pieces fit together, once the conclusions have time to settle, once you’ve collapsed the details into the abstraction, then the result can move into your long-term memory. That’s where all the details about your project live—you’re not figuring them out every time afresh, you’re just remembering your conclusions from earlier.
That means that despite the obvious similarity, there’s a big difference between this code:
sort(
values.begin(),
values.end(),
[](float a, float b) { return a < b; });
And this code:
processVector(
values.begin(),
values.end(),
[](float a, float b) { return a < b; });
I know what sort does. I know the abstraction, it’s in my long-term memory. I can nearly sight-read it—the only work is looking at the comparison function to see what the sort order will be. As a result, it doesn’t really take up a new short-term-memory slot to read sort . I knew values was a vector of floats; now I know values is a sorted vector of floats. That’s still one thought in my cache.
My reaction to processVector is entirely different. I haven’t seen it before, and I don’t know what it does. The name isn’t helpful—it’s a good demonstration of the power of a weak name. My only recourse is to go look at the processVector code, maybe by single-stepping into it, 5 in order to start figuring things out. I’m back to my painfully small budget of seven (plus or minus two) thoughts while I’m collapsing it to something simpler .
Common Knowledge Is Free; New Concepts Are Expensive
Your goal when writing code is to make it easy to understand, so it’s important to keep the difference between sort and processVector in mind. A reference to sort doesn’t stress the reader’s short-term memory, because they already know what sort does. A reference to processVector is different—in order to understand the code, the reader needs to dive into processVector to collapse it, and that’s going to stress their cache.
Code that uses abstractions or patterns that everyone on the team understands is much easier to read than code that invents new abstractions or patterns.
One takeaway from this is obvious—if you’re writing code, use the standard abstractions and patterns common on your team. Don’t invent new ones…unless you’re confident that the newly invented abstraction or pattern is strong enough that it will become standardized across your team.
For instance, in the Sieve of Eratosthenes example, I kept an array of flags (imaginatively named isMultiple ) marking which integers were known not to be prime because they were multiples of other numbers. This was a plain-old C-style array of bool values. It’s easy to see that it would be possible to abstract this into a “vector of bits” class, eking out a bit of storage and very slightly better memory-access patterns.
With a BitVector class, 6 the Sieve code might look like this:
vector<int> primes;
BitVector isMultiple(100);
for (int value = 2; value < isMultiple.size(); ++value)
{
if (isMultiple[value])
continue;
primes.push_back(value);
for (int multiple = value;
multiple < isMultiple.size();
multiple += value)
{
isMultiple[multiple] = true;
}
}
Is this easy to read? Well, if the BitVector class is a standard part of your team’s armamentarium, something that everyone knows, then sure! It might even be easier than the version of the code that stored these flags as a simple array of bools.
Someone who doesn’t know BitVector is in a different boat. Well, a reckless programmer might just assume it’s, you know, a vector of bits, and sail forward. Reckless programmers tend to vote themselves off the island, though. A prudent programmer would investigate the BitVector class to make sure they understand it…and it’s not trivial, even in the simplest possible version that fits the preceding usage pattern:
class BitVector
{
public:
BitVector(int size) :
m_size(size),
m_values()
{
m_values.resize((size + 31) / 32, 0);
}
int size() const
{
return m_size;
}
class Bit
{
friend class BitVector;
public:
operator bool () const
{
return (*m_value & m_bit) != 0;
}
void operator = (bool value)
{
if (value)
*m_value |= m_bit;
else
*m_value *= ~m_bit;
}
unsigned int * m_value;
unsigned int m_bit;
};
Bit operator [] (int index)
{
assert(index >= 0 && index < m_size);
Bit bit = { &m_values[index / 32], 1U << (index % 32) };
return bit;
}
protected:
int m_size;
vector<unsigned int> m_values;
};
A real BitVector class would be more functional than this—and also bigger and more complicated, of course! Even at this level of functionality there’s trickiness, like creating a temporary object that wraps the ability to read and write a single bit, then relies on C++ operators to handle getting and setting the value. 7
That’s clever, 8 and it lets us write code that looks like simple array access even though it compiles to something more complicated. But sorting out the trick is going to use up slots in the reader’s short-term memory—their goal is to understand the Sieve code, not sort out the details of this weird BitVector class. For programmers who haven’t internalized what BitVector does—for programmers who haven’t collapsed and committed the BitVector abstraction to long-term memory—its use made the Sieve code harder to understand, not easier.
So if you were writing the Sieve code, 9 would it make sense to introduce a new BitVector class to handle the array of flags? No, almost certainly not! It’s unnecessary work, and it makes the code harder to read.
The only justification for introducing BitVector is if you know that it’s going to be used broadly enough in the codebase that everyone on the team will add it to their long-term memory, and that using it will have important advantages over preexisting solutions. And the only way you can know that is if you’ve identified a lot of places in the codebase where an array of bits is used, and you have identified (and hopefully measured!) the advantages and have a good reason for not just using vector<bool> . Then, and only then, does it make sense to introduce BitVector .
For what it’s worth, we do have a bit vector class at Sucker Punch, used in roughly 120 places in our fairly large codebase. It’s comfortable tech for most of the team—they’ve internalized what it does, so a reference to the bit vector class isn’t going to trigger an investigation. It’s part of our common knowledge, so it’s safe to use. But it wasn’t introduced based on one use case—we wrote it based on lots of examples of code working with large arrays of bits .
Putting It All Together
The best code—which is to say, the easiest code to read and understand—leverages how short-term and long-term memory work together. It leverages the standards and conventions of your team, because all of that stuff is already in everyone’s long-term memory. When new thoughts are introduced, they pop up in small-to-medium-sized chunks, small enough to fit inside the reader’s short-term memory. Those chunks have simple, easily abstracted functionality and carefully chosen names, which makes them easy to collapse and commit to long-term memory .
The result? A codebase that is easy to read and easy to learn—that makes it easy to collapse new ideas into simple abstractions, then does the same thing with those abstractions recursively until the whole codebase is clear.
1 Or maybe working memory , if you’ve chosen that side in the ongoing debate among cognitive scientists. I’m actually on Team Working Memory, but short-term memory is a more widely known term, so that’s what I’m using.
2 I have experimentally determined that coffee does not affect the limit.
3 This is not a smart way to factor a number, by the way. It’s just an example. Rule 19 has a smarter version.
4 Actually there are dozens of dozens. That’s too many methods. We need to do some housekeeping.
5 Stepping through code in the debugger is an excellent way to understand it better. 10/10, would recommend. It doesn’t fundamentally change the need for short-term memory, but the debugger can be a crutch to help you remember or quickly regenerate thoughts, like what all the variables are and what values they hold.
6 The BitVector class in this chapter is (in spirit, at least) a simplified version of C++’s vector<bool> .
7 The primary function of C++ sometimes seems to be allowing you to pack a universe of complexity into every raindrop of code. But I digress.
8 Not a compliment.
9 Please don’t generate prime numbers this way, though. Humanity has invented much better ways of generating primes in the intervening 2,250 years. Hats off to Eratosthenes, though! The Sieve is the third or fourth most impressive thing on his resume, and I still know what it is.