Programming is an inherently creative, intellectually challenging activity. That’s a big part of why I love it, and you’d probably say the same. Every problem is different than the ones before, requiring a little bit of cleverness to solve—though, per the Rules in this book, hopefully not too much cleverness!

But not every problem has an elegant solution. Even the most exciting programming assignment has moments of drudgery: tasks that aren’t interesting, that it’s difficult to get excited about, that nobody wants to do. It’s easy to work on the exciting stuff instead, putting off the drudgery and secretly hoping that someone else on your team will take it on instead.

With that setup, the moral of this chapter will come as no surprise— don’t skip the drudgery . That unlovable task isn’t going anywhere. There’s no hidden army of code elves who’ll do the work while you’re sleeping. And half-completed tasks are a slow poison, working to kill your project.

The key is to know the danger signs. You’re a clever person, 1 more than clever enough to rationalize away the necessity of the tasks you don’t enjoy. That’s especially true if you have a long backlog of more interesting tasks to get to.

Knowing the sorts of tasks that you personally tend to ignore is a key bit of self-knowledge. Your list may not match mine, or match your coworkers’—one programmer’s drudgery is another programmer’s day at the park, to coin a phrase. Once you can identify which tasks you tend to avoid, you can be more conscious of giving them the priority they deserve.

That said, this would be a pretty empty chapter without some examples! They were not hard to find, since I could draw both from the kinds of tasks I personally dread and from the tasks I’ve seen others avoid.

A New Argument

Imagine that you’ve got a function like this:

vector<Character *> findNearbyCharacters(
    const Point & point,
    float maxDistance);

The function returns all characters within some bounding sphere. Dozens and dozens of calls to this function are scattered throughout your codebase. You’ve found a handful of places where the basic behavior of this function isn’t quite right. In these cases there are a handful of characters you’d like to exclude from the search, and you’ve decided to add a new argument to handle the exclusion:

vector<Character *> findNearbyCharacters(
    const Point & point,
    float maxDistance,
    vector<Character *> excludeCharacters);

Now you’re faced with a choice—do you update all the places the old code was called, adding the new argument? Or do you avoid this work by specifying a default argument, like this:

vector<Character *> findNearbyCharacters(
    const Point & point,
    float maxDistance,
    vector<Character *> excludeCharacters = vector<Character *>())
{
    return vector<Character *>();
}

Or perhaps avoid the work by having two overloaded versions of the function?

vector<Character *> findNearbyCharacters(
    const Point & point,
    float maxDistance);
vector<Character *> findNearbyCharacters(
    const Point & point,
    float maxDistance,
    vector<Character *> excludeCharacters);

Overloading and default arguments let you skip the work of updating existing uses of findNearbyCharacters . That’s good, right? You can get on with the stuff on your backlog.

Maybe, maybe not. Going through the places the old version of the function is called isn’t just about converting them—it’s also about looking at how those pieces of code are using the function. The chances are good that a few of them are excluding characters from the list—exactly what your new argument handles. These examples should be converted to use the new argument.

Imagine that soon thereafter, you run into the need for finer-grained filtering. Say that you want to find only nearby enemies that pose a threat, instead of all characters. You decide to add a simple filtering interface:

struct CharacterFilter
{
    virtual bool isCharacterAllowed(Character * character) const = 0;
};

vector<Character *> findNearbyCharacters(
    const Point & point,
    float maxDistance,
    CharacterFilter * filter);

Here’s a filter that accepts threatening enemies, but rejects allies and incapacitated characters:

struct ThreatFilter : public CharacterFilter
{
    ThreatFilter(const Character * character) :
        m_character(character)
        { ; }

    bool isCharacterAllowed(Character * character) const override
    {
        return !character->isAlliedWith(m_character) &&
               !character->isIncapacitated();
    }

    const Character * m_character;
};

Now you have another set of decisions to make. Add another overloaded version of findNearbyCharacters ? Or maybe two new overloaded versions: one with filtering and an excluded characters list, the other just with filtering? That would bring you up to three or four overloaded versions of the function. Seems complicated—three or four versions of the function to keep in sync? Confusion about where to set breakpoints? Things are starting to get out of hand .

It might be better to handle excluded characters with a filter instead. Implementing a CharacterFilter that checks a list of characters is trivial. That would keep the number of versions of the function under control, and you’ll likely find a few more uses of findNearbyCharacters that would be simpler with a filter:

struct ExcludeFilter : public CharacterFilter
{
    ExcludeFilter(const vector<const Character *> & characters) :
        m_characters(characters)
        { ;  }

    bool isCharacterAllowed(Character * character) const override
    {
        return m_characters.end() == find(
                                        m_characters.begin(),
                                        m_characters.end(),
                                        character);
    }

    vector<const Character *> m_characters;
};

Converting to using filters everywhere implies some work. There are dozens of places where findNearbyCharacters is called. All of the calling code has to be inspected, and at least some of it will get converted to the new filter model. That sounds like drudgery to me. Faced with that amount of work, it’s really tempting to live with three overloaded versions and just convert the code that has to be converted.

That’s a mistake—or, at best, a reasonable decision made for the wrong reasons. You’re trading off the short-term cost of inspecting and updating the existing code against the long-term benefit of a simpler, cleaner model for finding nearby characters.

As programmers, most of us have a tendency to tie-break in favor of short-term costs instead of long-term benefits, usually to our later chagrin. If you think you know what the right solution to a problem is, but you’re reluctant to do it because of the amount of work involved, just cowgirl up 2 and do the work.

There’s Never Just One Bug

Here’s another example . You stumble onto a bug—some bit of code is calling another bit of code incorrectly. That’s understandable, because the second bit of code has doubled down on its poor name choices by omitting any documentation:

void squashAdjacentDups(
    vector<Unit> & units, 
    unsigned int (* hash)(const Unit &));

Seems pretty straightforward—it looks like the function squashes out adjacent duplicate values using the provided hash function. And that’s almost what it does:

void squashAdjacentDups(
    vector<Unit> & units, 
    int (* hash)(const Unit &))
{
    int nextIndex = 1;

    for (int index = 1; index < units.size(); ++index)
    {
        if (hash(units[index]) != hash(units[nextIndex - 1]))
        {
            units[nextIndex++] = units[index];
        }
    }

    while (units.size() > nextIndex)
    {
        units.pop_back();
    }
}

The problem is that the hash argument to squashAdjacentDups is expected to return a fully unique value, given how the code is written. That’s not what a hash function does, though. Given two equivalent objects, the hash function returns the same hash value, but it also might return that hash value for another object that isn’t equivalent. You always have to check for equivalency after the hash values are compared, which squash doesn’t do.

The bug you’ve just fixed is a result of this quirk—the caller passed in a hash function, not a unique identifier function:

struct Unit
{
    int m_id;
    string m_firstName;
    string m_lastName;
    string m_userName;
};

unsigned int hashUnit(const Unit & unit)
{
    return combineHashes(
                hashString(unit.m_firstName),
                hashString(unit.m_lastName),
                hashString(unit.m_userName));
}

This almost always works, which is why the bug wasn’t caught earlier…but once two adjacent Units hashed to the same value, things broke.

So should you fix the bug and move on? Nope, not until the drudgery is out of the way.

First of all, you have to rename the hash argument. Its current name is a lie, and that’s going to cause more problems. Either use it like a real hash function, with a separate call to check actual equivalence, or rename the argument to reflect its actual usage.

Second, you should review all the other places where squashAdjacentDups is called. Odds are good that at least one of them is going to exhibit exactly the same bug you just fixed. In fact, there’s a decent chance that all of the callers of squashAdjacentDups will exhibit the bug. You’ve done the work to diagnose a pretty subtle bug, so leverage your new understanding to find the other instances of that bug in the code.

Fixing the name takes very little time—it’s easy to convince yourself to take that step. Reviewing all the other callers of squashAdjacentDups , on the other hand, is going to be a slog. But it will pay off—maybe not for you, but for someone on your team. Short-term pain, long-term benefit. Take your time, review the other callers, and fix the problems you find .

The Siren Call of Automation

Programmers have a predictable reaction to encountering some bit of drudgery: they want to automate it.

Automation can take many forms. Perhaps you could fiddle together a regular expression in your source editor to find all of the calls to findNearby​Charact⁠ers and insert a new argument. Or maybe it would be better to write some Python code to do this, since that would let you handle the exceptions more easily. For that matter, you’ve had to deal with this sort of argument-adding situation before—maybe what the project really needs is a generalized argument-adding utility app written in Python. That would be a good project; better get started on it!

Believe me, I get it. It’s more fun to noodle on a regular expression until it flawlessly handles every variation of whatever bit of drudgery you’re facing, or to write a bunch of clean-sheet Python code to do the same thing. It’s certainly a lot more fun than making the same manual edit over and over again. But it isn’t very smart. You’ll spend less time just making the edits by hand; do the math, per Rule 20 .

Maybe you can get a running start with regular expressions—hey, if there’s an easy, no-fiddling-required regular expression that solves 80% of the drudgery, by all means do it! You can sweep up the other 20% of the drudgery by hand.

Keep in mind that tasks like the examples presented here feel repetitive, but rarely are they so repetitive that they’re easily automated. There’s judgment involved, even if it’s as simple as breaking up a function call over multiple lines or adjusting a comment to match the new function signature.

Managing File Sizes

Code evolves over time—and despite the undeniable joys of deleting code, you’ll end up adding more code to your project than you end up deleting. In the process of adding code, your source files get longer and longer, maybe to the point of being uncomfortably long.

That may be a natural product of your team’s conventions. At Sucker Punch, by convention the source code for a particular class all resides in a single source file and a single header file. And, like a lot of teams, despite our best efforts we’ve ended up with a couple of kitchen-sink classes, like our main character class. It’s a convenient spot in the class hierarchy to add features, so lots of features have been added, and lots of features mean lots of source code. I just checked, and the implementation file for our main character class is 19,000 lines long. Ouch.

Is this a problem? Yeah, at least a little bit. It’s harder to work in a file that size. You have to use text search to find anything, as paging through the code gets you nowhere fast. It takes longer to compile than the other files, which throws off your build distribution. It’s hard to tell which bits of code are related to which other bits when they’re separated by thousands of lines.

So why hasn’t it been fixed? Because reducing the number of lines would involve a lot of drudgery: copying and pasting code to a new file, refactoring chunks of behavior into separate classes to respect our “one source file per class” convention, reexamining the header files in the old and new files to make sure they’re still appropriate, and resolving any dangling references after the files are moved. That work is zero fun, and we’re all busy. We’ve collectively decided to whistle past the graveyard, avoiding the drudgery and ignoring the increasingly unwieldy size of the file, even though we’d all be happier with a shorter version of the file.

I should note that the Sucker Punch team is well-adjusted, with everyone on the team showing their commitment every day to a clean and functional codebase. For the first two examples, everyone on the team would have chosen the hard path, powering through the drudgery to update code to match the new argument set or looking for bugs similar to the one that had just been fixed. But we still have a 19,000-line source file that we’re all faintly embarrassed about.

Look, it’s hard to dive into the drudgery, even for a disciplined team. The first step is to recognize that you’re avoiding a task because you don’t want to do it. The second step is to take a step back to evaluate the long-term benefits of tackling it—it’s entirely possible that the task is both unpleasant and not particularly valuable, in which case you certainly shouldn’t do it! But if it’s going to pay off in the long term, even though it’s going to suck in the near term, then it’s time for step three: hammer the nails .

There Are No Shortcuts

Imagine that you’ve got a big chunk of wood with a hundred nails sticking out of it. They make it impossible to use the chunk of wood for anything else. You could just ignore the nails. You could hope that someone else will hammer the nails for you. You could spend a lot of time tinkering with a nail-hammering machine that might work someday.

Or you could just take out your hammer and get to work. Sometimes you just need to hammer the nails.

1 You’ve made it to the last Rule in the book, which I’m taking as evidence of your wisdom and insight.

2 Or cowboy up, if that’s your style.