Any big codebase, especially one that’s been around a while, has dead ends in it: lines of code, or functions, or subsystems, that aren’t getting exercised any more. Presumably they were added for a reason—at one point, those lines of code were getting called. Things change, though, and at some point whatever code was calling no longer needs to. The calls stop coming. The code has been orphaned.
Sometimes the orphaning is obvious, like a function that isn’t called from anywhere else in the program. If your language and toolchain are robust enough, you might even get a warning about this particular kind of dead code.
More typically, the orphaned code isn’t that obvious. It might still be mechanical, like a virtual method defined in a base class that is never called for a particular derived class. Static analysis can’t pick up that sort of thing up. Or there’s code written to handle some special edge case in a function, a scenario that requires special conditional handling. At some point, things change and that scenario can no longer occur. The edge case code is still sitting there, but it’s never called.
The closer you look at any mature codebase, the more orphaned code you find—like enumerated values that are defined but never used, or special-case code targeted at an old version of a library you haven’t used for years.
This sort of evolution of code is both natural and inevitable. The codebase is a river, winding its way back and forth through its floodplain, occasionally shifting course. Sometimes when the course changes enough, an old part of the river is cut off. It still looks like a river, but now it’s a lake.
Let’s look at a simplified example of code evolution. Imagine you’ve got some code that tracks all the characters in a game. Through the course of the game’s development, your requirements for character tracking evolve, and the code evolves with it. We’ll check in at four points in this evolution.
Step 1: A Simple Beginning
Things start off simple. Your game instantiates an object for each character in the game, and that object exposes some simple querying methods, mostly about whether that character considers another character a threat or an ally :
struct Person
{
Person(Faction faction, const Point & position);
~Person();
bool isEnemy(const Person * otherPerson) const;
void findNearbyEnemies(
float maxDistance,
vector<Person *> * enemies);
void findAllies(
vector<Person *> * enemies);
Faction m_faction;
Point m_point;
static vector<Person *> s_persons;
static bool s_needsSort;
};
You maintain a list of all the characters in the game:
Person::Person(Faction faction, const Point & point) :
m_faction(faction),
m_point(point)
{
s_persons.push_back(this);
s_needsSort = true;
}
Person::~Person()
{
eraseByValue(&s_persons, this);
}
A “faction” is assigned to each character, and characters from different factions are considered enemies:
bool Person::isEnemy(const Person * otherPerson) const
{
return m_faction != otherPerson->m_faction;
}
You frequently need to find a character’s nearby enemies, so there’s a method for that:
void Person::findNearbyEnemies(
float maxDistance,
vector<Person *> * enemies)
{
for (Person * otherPerson : Person::s_persons)
{
float distance = getDistance(m_point, otherPerson->m_point);
if (distance >= maxDistance)
continue;
if (!isEnemy(otherPerson))
continue;
enemies->push_back(otherPerson);
}
}
You also need to know who a character’s allies are, so there’s a method for that, too. That method has a little bit of trickery—characters are sorted by faction, which puts all of the character’s allies together. You can early exit when you hit the end of the character’s allies:
bool compareFaction(Person * person, Person * otherPerson)
{
return person->m_faction < otherPerson->m_faction;
}
void Person::findAllies(vector<Person *> * allies)
{
if (s_needsSort)
{
s_needsSort = false;
sort(s_persons.begin(), s_persons.end(), compareFaction);
}
int index = 0;
for (; index < s_persons.size(); ++index)
{
if (!isEnemy(s_persons[index]))
break;
}
for (; index < s_persons.size(); ++index)
{
Person * otherPerson = s_persons[index];
if (isEnemy(otherPerson))
break;
if (otherPerson != this)
allies->push_back(otherPerson);
}
}
This all works—so you trundle along with a simple faction-based hostility model. Games can get pretty far with something this simple, by the way—if you added a function to decide which factions are hostile to which other factions, you’d have the exact hostility model for Sucker Punch’s inFamous series of games .
But while the hostility model seems to be sufficient, you soon outgrow the two query functions we started with, findNearbyEnemies and findAllies . Both are useful, but new problems arise that they don’t address. Maybe you want to find all allies to whom the player has a clear line of sight. You could do this by finding the player’s allies, then filtering out the ones the player can’t see:
vector<Person *> allies;
player->findAllies(&allies);
vector<Person *> visibleAllies;
for (Person * person : allies)
{
if (isClearLineOfSight(player, person))
visibleAllies.push_back(person);
}
You also might create more methods in Person to handle cases like this—easy enough to add a findVisibleAllies method, right? Then you wouldn’t need the intermediate list allies ; you could skip straight to visibleAllies . But that approach gets unwieldy as the number of find functions mounts. If you add a dozen increasingly specialized find functions to Person , most of which are called from exactly one place, then you’re not doing yourself any favors.
Step 2: Generalizing a Common Pattern
You’ve accumulated enough examples of this pattern (“find characters that match a certain set of criteria”) to feel confident generalizing, 1 so you add a template function to the Person class:
template <class COND>
void Person::findPersons(
COND condition,
vector<Person *> * persons)
{
for (Person * person : s_persons)
{
if (condition(person))
persons->push_back(person);
}
}
That lets you sidestep the extra memory allocations while still having reasonably legible code: 2
struct IsVisibleAlly
{
IsVisibleAlly(Person * person) :
m_person(person)
{ ; }
bool operator () (Person * otherPerson) const
{
return otherPerson != m_person &&
isClearLineOfSight(m_person, otherPerson) &&
!m_person->isEnemy(otherPerson);
}
Person * m_person;
};
player->findPersons(IsVisibleAlly(player), &allies);
Once the template is solid, you sweep through all the calls to Person::findNearbyEnemies and Person::findAllies in your codebase. When you find the multistage filtering idiom you used in the first line of sight example, you convert it to use the new findPersons template.
In this process of doing this sweep, you discover that every single one of the places you called findAllies was doing extra filtering, so you convert them all to findPersons . That’s a good thing—the code is simpler, faster, and easier to read. You’re happy with the results of this step. Your codebase is easier to read without all the multistage filtering. You keep trundling forward with a few findNearbyEnemies calls, a lot of findPersons calls, and zero findAllies calls.
But eventually you decide that your simple hostility model isn’t good enough. You decide to let players put on disguises. Your goal is to let the player put on a security guard’s uniform, then walk through a secured area without getting shot .
Step 3: Adding Disguises
Adding disguises also exposes the shortcomings of the simple hostility model you’ve used so far. Dividing the world into allies and enemies isn’t working so well. You really need to add something in between, to reflect the ambivalence many of the characters feel for each other. A security guard considers another security guard their ally, but a random tourist falls somewhere in between being an ally or an enemy.
It’s easy to abstract this more nuanced hostility model into a virtual interface:
enum class Hostility
{
Friendly,
Neutral,
Hostile
};
struct Disguise
{
virtual Hostility getHostility(const Person * otherPerson) const = 0;
};
You add a new method on Person to set the character’s current disguise, using nullptr to indicate the lack of any disguise:
void Person::setDisguise(Disguise * disguise)
{
m_disguise = disguise;
}
Obviously the isEnemy method is going to have to change a bit:
bool Person::isEnemy(const Person * otherPerson) const
{
if (otherPerson == this)
return false;
if (m_disguise)
{
switch (m_disguise->getHostility(otherPerson))
{
case Hostility::Friendly:
return false;
case Hostility::Hostile:
return true;
case Hostility::Neutral:
break;
}
}
return m_faction != otherPerson->m_faction;
}
And…that’s it, actually. All the other code we’ve written seems to work fine—no new bugs pop up, and disguises work as expected.
But there’s a problem lurking—the old Person::findAllies method no longer works. And we have no idea that it’s stopped working, because nobody is calling it. Adding disguises broke a subtle assumption in findAllies . It assumes that if we sort the whole list of characters on faction, then all of our allies will be adjacent to each other in the array. With disguises, that’s often the case, but not always the case.
You can’t count on code reviews to catch this sort of problem. Code reviews are good at finding problems in code that has changed, because that’s what the review focuses on. They’re not good at finding problems in code that hasn’t changed, because reviewers usually skip over all of that stuff.
This particular bug is nasty because it’s not even guaranteed to show up once we start creating and using disguises. As long as your allies form a contiguous range in the list of characters, everything works fine. And even when findAllies doesn’t work, it still returns a partial list of allies, so the failure isn’t necessarily obvious.
It’s entirely possible that this bug will stay hidden forever! I still find occasional bugs in code I wrote 25 years ago, and I’m pretty sure they weren’t the last bugs in that code. There are always more bugs still hiding in old code, waiting for things to change enough that these latent bugs become active ones. But things might never change in a way that exposes the latent bugs…so is this really a problem ?
Step 4: The Chickens Return Home to Roost
In this case, yes, because many months later your example evolves again. Someone is writing some debugging code that lists all of the player’s allies. The Person::findAllies method is perfect for this—so they call it in the obvious way :
vector<Person *> allies;
player->findAllies(&allies);
for (Person * ally : allies)
{
cout << ally->getName() << "\n";
}
This code certainly looks fine! If disguises haven’t been set, then it works perfectly. Even if disguises are being used, this code won’t break in an obvious way. Even when it doesn’t work perfectly, it will still list allies…it might not list all the player’s allies, but you’re less likely to notice a missing ally than an enemy popping up in the ally list. It’s entirely possible that this change sails through your code review process, too.
But in all those months where nobody was calling findAllies , some code was written that assumed the results returned from findPersons would be in a stable order. That was an easy assumption to make—the order was perfectly stable, after all! So the new code found a couple of nearby allies and had them follow in single file behind the player, and everything worked great. Now, for some bizarre reason, on rare and unpredictable occasions the followers all panic, scrambling to new places in the single file order. Which is unshippable.
The problem, of course, is that innocuous-looking findAllies call. If new characters have been added, then findAllies re-sorts the list of characters, unpredictably scrambling the order of the results of any call to findPersons . It’s going to be a serious hassle to review all of the places findPersons is called to look for problems .
Assigning Blame
So where did things go wrong?
It would be easy to point at Step 3 as the problem, because we clearly made a mistake in that step. We added disguises, but didn’t update findAllies to match. That was an easy mistake to make, though—the code we wrote worked perfectly, and nothing seemed to break. No amount of product testing would find the problem in findAllies since it’s not called anywhere. Even reviewing findAllies itself might not have helped—the assumption is a subtle one. 3
You might argue that there’s a mistake in Step 4, where we wrote new code that resurrected the use of the unused findAllies . That’s the name of this Rule, after all—“Code That Isn’t Running Doesn’t Work.” If I know that findAllies hasn’t been getting called, then I should definitely assume it doesn’t work.
That’s not the general assumption you’d make as a programmer, though, at least not if you’re working in a healthy codebase. When you’re writing some new bit of code or fixing some problem, you have to assume that the rest of the codebase pretty much works. If you see a bit of functionality, you expect it to operate as intended. It’s impossible to make progress otherwise.
The real mistake in this example was made in Step 2. When you orphaned findAllies , you created a problem. When you stopped calling it, it stopped working.
Now, that may sound ridiculous. At the point you orphaned it, the function still worked exactly as intended. Why would you discard perfectly functional code, throwing away the work it took to get it to that point? It clearly didn’t stop working until Step 3, right?
Maybe. It’s Schrödinger’s cat, right? Once we got past Step 2, the code wasn’t running anymore, so you don’t know whether it was working or not. In this example, it seems simple to spot the mistake—our orphaned function stopped working in Step 3, and we discovered this (at great cost) in Step 4. But in the real world, there were dozens of steps between Steps 2 and 4. I edited out all the ones that didn’t have an effect…but any one of them could have broken the orphaned function and we wouldn’t have known.
It’s simpler to assume that when we orphan something, it immediately stops working. Over time, this is almost certainly true. We just won’t know when it happens.
If we make this assumption, then the mistake in Step 2 wasn’t orphaning findAllies . It was not deleting findAllies when we orphaned it. When we stopped calling it, it stopped working. In Step 2, we made Steps 3 and 4 inevitable—the unexercised code was eventually going to break, and someone would eventually call it again. Much better to delete the orphaned code immediately.
The Limits of Testing
That’s not the standard answer to this problem, of course. If you work on a testing-centric team, you may have wondered why the unit tests didn’t catch the problem. If we have a full and complete set of unit tests, then findAllies isn’t really orphaned. It’s still getting called by our unit tests, so we wouldn’t have to assume that it immediately stopped working.
Unit tests are imperfect, though. There are good reasons why some teams don’t have unit tests for every bit of code. For one, testing is much more effective for some sorts of code than others. It’s easier to test simple stateless functions with obvious effects than more complicated, stateful stuff. If you’re testing the C standard libraries, it’s a lot easier to test strcpy than it is to test malloc . 4 Once things are stateful it’s a lot harder for your unit tests to exactly replicate the ways in which the codebase actually exercises things. Use cases will slip past your unit tests.
The test cases for findAllies were written when we wrote findAllies , long before we thought about adding disguises to the Person class. As a result, those test cases don’t exercise disguises. The findAllies function works fine as long as there are no disguises in place, so no problems are reported. It’s possible that the person adding disguises also realizes that the unit tests for findAllies need updating, and that they’ll add tests with the particular kind of disguises that break findAllies , and that the order of everything will exhibit the problem…but that’s a big ask.
There’s also a cost involved for the unit test. We have to keep the unit tests for findAllies up-to-date. There’s going to be some cost to running those tests. And for what? To make sure a function that no one is calling keeps working?
Ah, you say…but didn’t I just claim that Step 2 (orphaning findAllies ) made Step 3 (breaking findAllies ) and Step 4 (tripping over the broken code) inevitable? When we orphaned the code in Step 2, we made it inevitable that we would create a bug in the orphaned code, and that someone would eventually call the orphaned code and trigger the bug. Surely it would be good to write a solid unit test so that we’re more likely to detect any bugs we create, and to make it more likely that the orphaned function still works when someone eventually calls it?
Well—no. That’s the point of deleting the orphaned code in Step 2. Since the code has been deleted, we don’t have to worry about bugs sprouting in it, so there’s no Step 3. We also don’t have to worry about coders deciding to call it—it doesn’t exist, so there’s nothing to call, so there’s no Step 4.
Instead, the coders will call findPersons , which works perfectly:
struct IsAlly
{
IsAlly(Person * person) :
m_person(person)
{ ; }
bool operator () (Person * otherPerson) const
{
return otherPerson != m_person &&
!m_person->isEnemy(otherPerson);
}
Person * m_person;
};
vector<Person *> allies;
player->findPersons(IsAlly(player), &allies);
Recognizing that a bit of code has been orphaned and can be safely removed should spark joy. 5 Seriously, this should be the happiest moment in your week . You’re reducing the amount of code in your project, which makes everything easier, without reducing functionality in any way. It’s quick, it’s easy, and everyone is better off.
1 Where “enough” is “at least three,” per Rule 4, “Generalization Takes Three Examples” .
2 You could use a lambda here, too, of course, if your team has joined the Lambda Generation.
3 If you just shouted “Where’s your unit test?!?” at the book, hang tight. I’ll get there.
4 The standard function strcpy copies a C-style string to a new home. It’s simple and completely stateless. The standard function malloc is the general-purpose memory allocator for C. It manages all dynamically allocated objects (plus or minus) in your code. It’s very complicated and nothing but state.
5 If it helps, remind yourself that you can always retrieve the deleted code from your source control system. You won’t, but maybe the fact that you could will lead you to do the right thing.