Here’s an incredibly oversimplified but still useful model for thinking about code. Imagine that there are two kinds of programming problems to be solved—Easy and Hard.
You’ve already got an idea of what an Easy problem is, but let me give you some generic examples: Finding the largest and smallest values in an array of numbers. Inserting a node into a sorted binary tree. Removing odd values from an array.
Hard problems are also easy to identify: memory allocation, for instance—implementing the C standard library’s malloc and free . Parsing a scripting language. Writing a linear-constraints problem solver.
Now, Easy and Hard, as I’ve defined them here, are really only two points on a spectrum, and they aren’t even the extreme points. Some problems are trivial, even easier than the Easy examples—summing two numbers, say. And there are problems much harder than the Hard examples, like creating a journaling filesystem from scratch.
But they’re two useful points. Between Easy and Hard lie most of the problems programmers solve every day. For what it’s worth, I’ve written solutions to all of these examples—except building a journaling filesystem from scratch, although that sounds like fun.
It seems obvious that you’re going to need to write more code to solve a Hard problem than to solve an Easy one, and that the code you’ll write will be more complicated. This is often the case. Solutions to Hard problems are usually more difficult to write, and end up longer and more complicated than solutions to Easy problems.
That leads to another oversimplified model. This time, imagine that there are two kinds of solutions to problems: Simple and Complicated. Simple solutions are short and easy to understand. Complicated solutions are long and difficult to understand. Again, these are just two points on a spectrum. There are obviously Moderately Complicated or Simple-ish solutions, too, but it’s useful to think about the Simple and Complicated points on that spectrum.
You’re a programmer, so at this point you’ve figured out how we get to four flavors of code ( Table 14-1 ), per the Rule title.
Table 14-1. Simple and Complicated solutions to Easy and Hard problems | | Easy problem | Hard problem | | --- | --- | --- | | Simple solution | Expected | Aspirational | | Complicated solution | Really, really bad | Accepted |
It’s obvious that there are Simple solutions to Easy problems, and that there are Complicated solutions to Hard problems. From personal experience, we can all attest that it’s distressingly easy to write Complicated solutions to Easy problems. And, in some cases, it’s possible to write Simple solutions to Hard problems.
Per Rule 1 , we’d like to find solutions that are as simple as possible, so it’s clear where this Rule is headed! But let’s look at some examples.
Easy Problem, Simple Solution
Let’s start with an example of an Easy problem—finding the largest and smallest values in an array. Here is a Simple solution to this Easy problem:
struct Bounds
{
Bounds(int minValue, int maxValue)
: m_minValue(minValue), m_maxValue(maxValue)
{ ; }
int m_minValue;
int m_maxValue;
};
Bounds findBounds(const vector<int> & values)
{
int minValue = INT_MAX;
int maxValue = INT_MIN;
for (int value : values)
{
minValue = min(minValue, value);
maxValue = max(maxValue, value);
}
return Bounds(minValue, maxValue);
}
The algorithm is simple—it just loops through the values, tracking the largest and smallest values it finds. There’s some very minor subtlety about how to get started—I’m using a fairly standard trick to make sure the first element sets both minValue and maxValue . Other than that, the code is easy to follow and understand. It’s appropriately simple.
Easy Problem, Three Complicated Solutions
It’s entirely possible to take exactly the same algorithm and make the code much more complicated. We’ve all seen code that buries a simple algorithm under multiple layers of abstractions, like this:
enum EmptyTag
{
kEmpty
};
template <typename T> T MinValue() { return 0; }
template <typename T> T MaxValue() { return 0; }
template <> int MinValue<int>() { return INT_MIN; }
template <> int MaxValue<int>() { return INT_MAX; }
template <class T>
struct Bounds
{
Bounds(const T & value)
: m_minValue(value), m_maxValue(value)
{ ; }
Bounds(const T & minValue, const T & maxValue)
: m_minValue(minValue), m_maxValue(maxValue)
{ ; }
Bounds(EmptyTag)
: m_minValue(MaxValue<T>()), m_maxValue(MinValue<T>())
{ ; }
Bounds & operator |= (const T & value)
{
m_minValue = min(m_minValue, value);
m_maxValue = max(m_maxValue, value);
return *this;
}
T m_minValue;
T m_maxValue;
};
template <class T>
struct Range
{
Range(const T::iterator & begin, const T:: & end)
: m_begin(begin), m_end(end)
{ ; }
const T & begin() const
{ return m_begin; }
const T & end() const
{ return m_end; }
T m_begin;
T m_end;
};
template <class T>
Range<typename vector<T>::iterator> getVectorRange(
const vector<T> & values,
int beginIndex,
int endIndex)
{
return Range<vector<T>::const_iterator>(
values.begin() + beginIndex,
values.begin() + endIndex);
}
template <class T, class I>
T iterateAndMerge(const T & init, const I & iterable)
{
T merge(init);
for (const auto & value : iterable)
{
merge |= value;
}
return merge;
}
void findBounds(const vector<int> & values, Bounds<int> * bounds)
{
*bounds = iterateAndMerge(
Bounds<int>(kEmpty),
getVectorRange(values, 0, values.size()));
}
This is exactly the same algorithm, though there’s a lot to dig through to convince yourself of that. The code is well-meaning, at least. There’s nothing egregious here—we’re not exploiting any particularly weird quirks of C++, with template specialization being as fancy as things get. The names are all descriptive. You can imagine the justification for each line, with a little squinting.
And yet…it’s four times as much code, and it’s a lot harder to follow and understand than the simple example we started with. It’s Complicated code, at least relative to the problem we’re solving. Our previous example was appropriately Simple; this example is inappropriately Complicated.
That’s only one way to overcomplicate the solution, obviously. We’ve also all seen code that oversteps the problem it attempts to solve:
struct Bounds
{
Bounds(int minValue, int maxValue)
: m_minValue(minValue), m_maxValue(maxValue)
{ ; }
int m_minValue;
int m_maxValue;
};
template <class COMPARE>
int findNth(const vector<int> & values, int n)
{
priority_queue<int, vector<int>, COMPARE> queue;
COMPARE compare;
for (int value : values)
{
if (queue.size() < n)
{
queue.push(value);
}
else if (compare(value, queue.top()))
{
queue.pop();
queue.push(value);
}
}
return queue.top();
}
void findBounds(const vector<int> & values, Bounds * bounds)
{
bounds->m_minValue = findNth<less<int>>(values, 1);
bounds->m_maxValue = findNth<greater<int>>(values, 1);
}
Here we’ve chosen to solve a more general problem, finding the N th largest (or smallest) number in an array, and then finding the min and max values as a special case. This sort of overly general approach is almost always misguided. Yes, there’s not that much extra code, and it’s more fun to write something clever like this than a simpler solution, but it’s a lot harder to read. 1
Finally, it’s possible to overcomplicate things by getting the algorithm wrong. That’s hard to do in this case, since the simple solution is pretty obvious, but we’ve all seen code that misses the easy algorithm:
struct Bounds
{
Bounds(int minValue, int maxValue)
: m_minValue(minValue), m_maxValue(maxValue)
{ ; }
int m_minValue;
int m_maxValue;
};
int findExtreme(const vector<int> & values, int sign)
{
for (int index = 0; index < values.size(); ++index)
{
for (int otherIndex = 0;; ++otherIndex)
{
if (otherIndex >= values.size())
return values[index];
if (sign * values[index] < sign * values[otherIndex])
break;
}
}
assert(false);
return 0;
}
void findBounds(const vector<int> & values, Bounds * bounds)
{
bounds->m_minValue = findExtreme(values, -1);
bounds->m_maxValue = findExtreme(values, +1);
}
So, in all, these are three pretty commonplace ways to make things more complicated than they need to be: using too much abstraction, adding too much generality, and choosing the wrong algorithm .
The Cost of Complexity
There’s a real cost to extra complexity. It takes longer to write complicated code than simple code, and much longer to debug it. Anyone reading the code has to fight their way through the complexity to understand what’s going on. Our Simple solution has none of these problems—it’s easy to get it right the first time, and it’s easy to glance at it and understand both how it works and that it’s correct.
In fact, this single issue—do you solve Easy problems with Simple solutions?—is the best discriminator between mediocre programmers and good ones. When we interview candidates at Sucker Punch, we look for two things: can the candidate solve Hard problems, and do they write Simple solutions for Easy problems? Unless the answer is yes to both of these questions, we’re not interested.
Someone writing Complicated solutions to Easy problems isn’t just making their own job harder, they’re making it harder for everyone else on the team. Not only do their solutions take more time to create and introduce more bugs into the codebase, those solutions are more difficult and frustrating for everyone else to work with. We can’t afford that .
The Four (But Really Three) Kinds of Programmers
Just like there are four flavors of code—Easy and Hard problems, Simple and Complicated solutions—there are four kinds of programmers. Given an Easy problem, do you write a Simple answer or a Complicated solution? And given a Hard problem, is your solution Simple or Complicated?
Now it turns out that there really aren’t coders who write Simple solutions to Hard problems but Complicated solutions to Easy ones. That leaves us with three kinds of programmers, as Table 14-2 makes clear.
Table 14-2. Three kinds of programmers | Kind of programmer | Easy problem | Hard problem | | --- | --- | --- | | Mediocre | Complicated | Complicated | | Good | Simple | Complicated | | Great | Simple | Simple |
The difference between mediocre programmers and good ones is that good programmers write Simple answers to Easy problems. The difference between good programmers and great ones is that even as the problem gets Harder, the great programmer still finds a Simple solution.
At some point, problems get Hard enough that there are no Simple solutions to be found. The best measure of a programmer, then, is how far along this spectrum they can go before their solutions start getting Complicated. The farther along the spectrum they make it and the Harder the problems they can solve with Simple solutions, the better they are as a programmer.
In fact, you can look at this another way. The core skill of a great programmer is that they recognize when a problem that seems Hard is actually Easy, if considered from the right perspective.
Hard Problem, Somewhat Complicated Solutions That Don’t Work
Consider the problem of checking whether any permutation of a particular set of letters (let’s say “abc”) appears in a string. That is, given a “permute string” that represents a set of letters, does some ordering of those letters appear consecutively in another “search string”? For the permute string abc , the function should return true if the search string is cabbage or abacus , but false if the search string is scramble or brackish .
It’s not obvious how to solve this, right? The most obvious thing to do would be to generate all the permutations of the set of letters, then check whether any of them appear in the string. Generating permutations recursively is pretty simple. Grab each character from the permute string in turn, prepending it to all the permutations of the remaining characters in the search string. Here’s a first attempt at this:
vector<string> generatePermutations(const string & permute)
{
vector<string> permutations;
if (permute.length() == 1)
{
permutations.push_back(permute);
}
else
{
for (int index = 0; index < permute.length(); ++index)
{
string single = permute.substr(index, 1);
string rest = permute.substr(0, index) +
permute.substr(
index + 1,
permute.length() - index - 1);
for (string permutation : generatePermutations(rest))
{
permutations.push_back(single + permutation);
}
}
}
return permutations;
}
bool findPermutation(const string & permute, const string & search)
{
vector<string> permutations = generatePermutations(permute);
for (const string & permutation : permutations)
{
if (search.find(permutation) != string::npos)
return true;
}
return false;
}
The logic here is pretty simple, and things seem to work…until the permute string gets a teensy bit long. At that point things explode. The number of permutations is factorial in the length of the string, so our findPermutation function quickly becomes unusable. Give it a list of four characters to permute, as in our example, and it’s happy as a clam. Give it a dozen and it disappears into a recursive hole, never to return. 2
A naive reaction to this explosion would be to realize that I’m doing extra work. If any of the characters in the list are duplicated, then I’ll have duplicate entries in the list of permutations. Maybe eliminating duplicates from the list of permutations would help:
vector<string> generatePermutations(const string & permute)
{
vector<string> permutations;
if (permute.length() == 1)
{
permutations.push_back(permute);
}
else
{
for (int index = 0; index < permute.length(); ++index)
{
string single = permute.substr(index, 1);
string rest = permute.substr(0, index) +
permute.substr(
index + 1,
permute.length() - index - 1);
for (string permutation : generatePermutations(rest))
{
permutations.push_back(single + permutation);
}
}
}
sort(
permutations.begin(),
permutations.end());
permutations.erase(
unique(permutations.begin(), permutations.end()),
permutations.end());
return permutations;
}
Yeah, not so much. I didn’t add that much code, which is great, and the code I added is simple, but I didn’t really address the core problem. It’s not possible to optimize your way out of a factorial mess. Unless all of our sets of characters to permute are small or are mostly duplicated letters, this code is still unworkable.
Hard Problem, Somewhat Complicated Solution
A better change is to let go of the idea that we’re going to generate all the permutations. That approach is doomed.
Instead, we need to invert the way we’re thinking about the problem. Let’s check each substring of the search string. If we can match each character in the permute string to a single character in that substring, then we’ve found a permutation:
bool findPermutation(const string & permute, const string & search)
{
int permuteLength = permute.length();
int searchLength = search.length();
vector<bool> found(permuteLength, false);
for (int lastIndex = permuteLength;
lastIndex < searchLength;
++lastIndex)
{
bool foundPermutation = true;
for (int searchIndex = lastIndex - permuteLength;
searchIndex < lastIndex;
++searchIndex)
{
bool foundMatch = false;
for (int permuteIndex = 0;
permuteIndex < permuteLength;
++permuteIndex)
{
if (search[searchIndex] == permute[permuteIndex] &&
!found[permuteIndex])
{
foundMatch = true;
found[permuteIndex] = true;
break;
}
}
if (!foundMatch)
{
foundPermutation = false;
break;
}
}
if (foundPermutation)
return true;
fill(found.begin(), found.end(), false);
}
return false;
}
This works, though the logic of the nested loops is a little tangled. You might get twinges of performance anxiety seeing the three nested loops—our first attempt at this function failed because of performance, after all—but in practice the N 3 -ness of this approach isn’t an issue. Unless the permute string is a thousand characters long, performance won’t be the problem here.
If there’s an issue here, it’s the complexity of the logic. This is a Simple example, sized to fit this book, so the problem we’re solving isn’t actually that Hard. You might hope that we could find a Simple solution to it, and the preceding solution doesn’t quite qualify. It’s the sort of solution a Good programmer would write—completely functional, but more complicated than it needs to be.
Actually , a more typical solution from a Good programmer would include a spasm of premature optimization to avoid the three nested loops. They might keep running counts, for instance, then hash the set of counts to roughly linearize the function:
#define LARGE_PRIME 104729
bool findPermutation(const string & permute, const string & search)
{
int permuteCounts[UCHAR_MAX] = {};
int currentCounts[UCHAR_MAX] = {};
int permuteHash = 0;
int currentHash = 0;
for (unsigned char character : permute)
{
++permuteCounts[character];
permuteHash += character * (character + LARGE_PRIME);
}
int permuteLength = permute.length();
int searchLength = search.length();
if (searchLength < permuteLength)
return false;
for (int searchIndex = 0; searchIndex < permuteLength; ++searchIndex)
{
unsigned char character = search[searchIndex];
++currentCounts[character];
currentHash += character * (character + LARGE_PRIME);
}
for (int searchIndex = permuteLength;; ++searchIndex)
{
if (currentHash == permuteHash)
{
bool match = true;
for (char character : permute)
{
if (permuteCounts[character] != currentCounts[character])
match = false;
}
if (match)
return true;
}
if (searchIndex >= searchLength)
break;
unsigned char removeCharacter = search[searchIndex - permuteLength];
unsigned char addCharacter = search[searchIndex];
--currentCounts[removeCharacter];
currentHash -= removeCharacter * (removeCharacter + LARGE_PRIME);
++currentCounts[addCharacter];
currentHash += addCharacter * (addCharacter + LARGE_PRIME);
}
return false;
}
Again, this is functional, just overly Complicated. Under some conditions, it will have better performance than the last solution…but that doesn’t matter. The last solution had perfectly reasonable performance and is easier to understand .
Hard Problem, Simple Solution
But is there a simpler solution, one that’s easy to read and understand? What separates Great programmers from Good programmers is finding those sorts of solutions.
In this case, the algorithm we’re using is fine—checking each substring of the search string to see whether it’s a permutation of the permute string—it’s our expression of that algorithm that’s getting tangled. But there’s a simpler way to think about checking for a match.
If we standardize the order of the letters in the permute string, then similarly standardize the order of each substring we compare it to, we can just compare the two standardized strings:
bool findPermutation(const string & permute, const string & search)
{
int permuteLength = permute.length();
string sortedPermute = permute;
sort(sortedPermute.begin(), sortedPermute.end());
for (int index = permuteLength; index < search.length(); ++index)
{
string sortedSubstring = search.substr(
index - permuteLength,
permuteLength);
sort(sortedSubstring.begin(), sortedSubstring.end());
if (sortedPermute == sortedSubstring)
return true;
}
return false;
}
We haven’t changed the fundamental algorithm here, but expressing it this way makes it much easier to understand. It’s Simple where the last example was Complicated. A Great programmer finds simple and clear solutions like this one—and realizes that simplicity and clarity are almost always the important issues . The Greatest programmer isn’t the one who can write the most complicated code: it’s the one who finds the simplest answers to the most complicated problems.
1 Its performance is atrocious, too, but having told you not to worry about optimization in Rule 5 , I feel duty-bound to demote the performance concern to a footnote. In my defense, the simplest solution here is the fastest, and that is not uncommon.
2 Well, not “never.” With 4 letters, generatePermutations is so fast it’s hard to measure on my PC. With 8 letters, it takes about a hundredth of a second. With 12 letters, I had to wait 42 seconds, during which my PC’s fan kicked on full blast in a desperate attempt to stop me from melting something.