There’s a lot of focus in this book about making your code easier to read, whether it’s by being careful about hiding the behavior of your code behind extra abstractions, choosing good names for things, or choosing the simplest workable approach to a problem. Writing code that’s easy to read makes everything else go more smoothly, since we all spend a lot more time reading and debugging code than we spent writing it in the first place. When you’re debugging a bit of code, it’s much easier to figure out what’s going wrong when you have a quick way to understand what it’s trying to accomplish.

That’s especially true for a project you’re working on as part of a team, but it’s even true for a solo project. If you’ve got a nontrivial solo project going, one that you’re spending weeks or months or even years on, you’ll end up needing to refamiliarize yourself with code you wrote long before. Whatever thoughts you had in your head when you wrote that code will have faded away; all that’s left will be the code itself. At this point, you’re in pretty much the same place as a coworker on a group project: you need to sort out what the code is doing (or trying to do) by reading it.

Here’s another way of thinking about this—Future You is a stranger.

Unless your project will get wrapped up and thrown away in a day or two, expect to come back to your code as a stranger. Do Future You a favor and make it easy to read.

Imagine walking someone through some bit of code you’ve written. If your team does code reviews (and it should; see Rule 6 ), then you’re probably used to doing that. You talk about what this code is trying to accomplish, how it fits into the larger scope of the project, and why you made the decisions you did. You point out any bits of trickiness or cleverness (hopefully there aren’t many), note any issues that haven’t been taken care of yet, walk through how the pieces fit together, and probably narrate the control flow through the individual functions you’ve written.

In short, you’re telling the story of your code. The better a job you do of telling that story, the more quickly and completely your audience will understand that code. And in a perfect world, the code would tell its own story, without your narration.

That’s a pretty lofty target, especially if your code has to be a little bit complicated to solve its target problem. Nevertheless, code that tells its own story is what you should always be shooting for.

Don’t Tell Stories That Aren’t True

So—what does it mean for code to tell its own story? I’ve touched on some of the important concepts, like choosing good names ( Rule 3 ), and making the intent of your code as simple and obvious as possible ( Rule 1 ). After all, it’s much easier to follow a simple story than it is to follow a complicated one!

I haven’t really addressed formatting or commenting yet in this book—the code examples accompanying the Rules are largely comment-free. That’s not a statement on my part—in this book I can write whole paragraphs of text explaining the code examples, so keeping them comment-free and compact makes sense. In real code, comments can be a huge help for code readability.

That doesn’t mean all comments are good, though! It’s entirely possible for comments to do more harm than good. Some comments are never true to begin with; others were true when the comment was written, but reality has since drifted away.

Here’s an example:

void postToStagingServer(string url, Blob * payload)
{
    // Will always get a valid handle back due to Connect::Retry

    ConnectionHandle handle = connectToStagingServer(
                                url,
                                Connect::Retry | Connect::InternalServer);

    // Post data 

    postBlob(handle, payload);
}

This seems pretty simple, but it’s not—the first comment is wrong. When the code was written, the Connect::Retry flag guaranteed success. Things got more complicated when the (imaginary, in this case) team decided that there were no situations in which infinite retry (hanging until a successful connection was made) was a good strategy. The behavior of Connect::Retry changed, but this bit of code, which relied on the old behavior, didn’t change to match.

So now there’s a bug in PostToStagingServer , but one that doesn’t show up very often, because ConnectToStagingServer almost always works. Pity the poor programmer who’s trying to debug this, especially if PostBlob is written to be robust against the empty handle that ConnectToStagingServer returns in error cases. The poor programmer reads the code, sees the comment, accepts it, and moves on, missing the actual problem.

If not for that comment, the bug would have been found sooner, because it would have been obvious that an error was possible. It’s this sort of situation that leads some programmers to argue that all comments are bad, insisting that the problems caused by out-of-date comments outweigh the benefits of accurate ones.

Remember that code that isn’t running doesn’t work, per Rule 8 . If some bit of code isn’t getting exercised frequently, it will stop working, and you won’t know that it’s stopped working because it isn’t getting run.

In some sense, comments are code that never runs—the closest they come to running is when someone reads through and compares the comments to the actual code. That doesn’t happen very often, and generally isn’t very thorough when it does, so it shouldn’t be a surprise that comments “stop working” as the functionality of the code they describe slowly drifts out of touch with the comment.

The easiest way to avoid this is to change the comment into an assert. Don’t mention in a comment that one of the arguments to a function is expected to be non-null—assert that it is. Or in this case, don’t claim that ConnectToStagingServer always returns a valid handle—assert that it does. You’ve told the same story, just in a much more effective way.

Make Sure There’s a Point to the Story

Sometimes comments aren’t wrong—they’re just useless. We’ve all seen less-than-informative comments, often as an unintended result of some fixed commenting style that all code on your project must follow. Here’s an example of code that adheres to a project-wide dictate that all functions must be documented with Doxygen. 1 The comment here follows the rule without actually passing along any information:

/**
* @brief Post payload to staging server
* 
* Attempt to post the given payload to the staging server at the
* given address, returning @c true if the post is successful and
* @c false if it fails for some reason.
* 
* @param url URL to server
* @param payload Data to post
* @returns true on success
*/
bool tryPostToStagingServer(string url, Blob * payload);

Nothing in that comment is wrong—it’s just not very useful. We can assume that the “try” at the beginning of the function name is a project convention that marks functions that return true on success. If that’s the case, then all of the information in the comment is directly implied by the function declaration. The comment isn’t adding anything new; it just restates the function name, then restates it, then restates it again.

If the comment accompanies the declaration of a function rather than its definition, as in this example, then the space taken up by fixed-format comments can quickly overwhelm the space devoted to actual function declarations. That’s the cost of this commenting style—the comments make it hard to find the actual code. This is exacerbated by whatever awkwardness pops up in the comment itself as it fits itself to the format—those @c s in the comment aren’t helping readability. 2

There is a potential upside—the point of Doxygen isn’t just the comments, it’s also the documentation that’s generated from them. That documentation isn’t as useful as it once was, now that editors are much better at hyperlinking back and forth within projects, but it can still be useful if done thoughtfully.

That’s usually not the case, though. Programmers in a hurry write hurried comments, not thoughtful ones. They aim to meet mechanical standards before moving on, which produces comments that are correct but uninformative, like the one in this section. A list of uninformative entries for individual functions and types doesn’t make for a useful introduction or reference to the code—you’re not learning anything you wouldn’t learn from reading through the code .

Telling Good Stories

So what makes a good comment?

The most obvious answer is that a good comment tells the reader something about the code that isn’t obvious . A comment that recapitulates the obvious, like the prior example, is correct but not very useful. A good comment, one that helps the reader understand the code, might explain why the code is written the way it is, give the expected usage for a function, or mark some bit of logic that might need further work.

There’s another important role that good comments fill—they punctuate the code. They tell you what parts of the code fit together and separate bits of code that represent separate thoughts. In this way, they act like spaces and punctuation in writing. Youcanreadsentencesthatdontincludespacingorpunctuation…but it’s a lot easier to read sentences that do, right? The spaces break up the words. Punctuation breaks up sentences and clauses. Paragraphs break separate thoughts.

The same is true of code, with spacing and comments filling the roles that spacing and punctuation do in normal writing. Here’s an example. (I’m exaggerating the point here by using a super-compact naming style for variables and compressing out more whitespace than you’d normally see.)

bool findPermutation(const string & p, const string & s)
{
    int pl = p.length(), sl = s.length();
    if (sl < pl) return false;
    int pcs[CHAR_MAX] = {}, scs[CHAR_MAX] = {};
    for (unsigned char c : p)
    { ++pcs[c]; }
    int si = 0;
    for (; si < pl; ++si)
    { ++scs[static_cast<unsigned char>(s[si])]; }
    for (;; ++si)
    {
    for (int pi = 0;; ++pi)
    {
    if (pi >= pl) return true;
    unsigned char c = p[pi];
    if (pcs[c] != scs[c]) break;
    }
    if (si >= sl) break;
    --scs[static_cast<unsigned char>(s[si - pl])];
    ++scs[static_cast<unsigned char>(s[si])];
    }
    return false;
}

It’s certainly possible to figure out what this function is doing—it has a descriptive name, at least, so you’ve got a head start. Adding more descriptive names, spacing to separate thoughts, and comments to explain those thoughts will make it much easier to read:

// Check whether any permutation of the permute string appears in the 
//  search string 

bool tryFindPermutation(const string & permute, const string & search)
{
    // If the search string is shorter than the permute string, then there's 
    //  no way it can be a permutation. Exit now to simplify things.

    int permuteLength = permute.length();
    int searchLength = search.length();
    if (searchLength < permuteLength) 
        return false;

    // Count how many times each letter shows up in the permute string.
    //  We'll compare these counts to running counts we'll keep in the 
    //  search string.

    int permuteCounts[UCHAR_MAX] = {};
    for (unsigned char c : permute)
    { 
        ++permuteCounts[c]; 
    }

    // Make the same counts for the first possible match in the
    //  search string

    int searchCounts[UCHAR_MAX] = {};
    int searchIndex = 0;

    for (; searchIndex < permuteLength; ++searchIndex)
    { 
        unsigned char c = search[searchIndex];
        ++searchCounts[c]; 
    }

    // Loop over the possible matching substrings in the search string

    for (;; ++searchIndex)
    {
        // Check whether the current substring matches the permute string

        for (int permuteIndex = 0;; ++permuteIndex)
        {
            // If we didn't find any character count mismatches after we've
            //  checked all the characters in the permute string, then we've
            //  found a permutation. Return true to mark that success.

            if (permuteIndex >= permuteLength) 
                return true;

            // If the count of this character in the permute string doesn't 
            //  match the count in this substring of the search string, then 
            //  the substring isn't a permutation. Move on to the next one.

            unsigned char c = permute[permuteIndex];
            if (permuteCounts[c] != searchCounts[c]) 
                break;
        }

        // Stop once we've checked all possible substrings in the
        //  search string

        if (searchIndex >= searchLength)
            break;

        // Update the running character counts to match the next
        //  possible match

        unsigned char drop = search[searchIndex - permuteLength];
        unsigned char add = search[searchIndex];

        --searchCounts[drop]; 
        ++searchCounts[add];
    }

    // If we make it here, then we're out of substrings and didn't find 
    //  any matching permutations, since we return immediately once 
    //  they're found.

    return false;
}

Much easier to follow, right? Read the previous example and you’re in for some tough sledding figuring what’s going on. Read this example from top to bottom, and you understand exactly what it’s doing and why.

The extra spacing breaks up the bits of logic, just like spaces break up words in a sentence. Indentation groups related thoughts. Choosing good names for variables is a shortcut to understand their purpose—good names are your first and most important bit of documentation. Comments provide context and explanation—they focus on the big picture, the “why” to the code’s “what .”

If you’re used to explaining code or having it explained to you, then reading code written this way feels familiar. Good comments feel like reading a story .

You could also think of good code as a song. Songs have music and lyrics, with each playing complementary roles. Good code is the same way—the actual code and the comments have separate but related roles. They support each other. The lines of code are the functioning part; good naming and formatting make the function of each line clear. The comments support this with context, explaining how the lines fit together and what the purpose of each line is.

Your code editor probably color-codes things, with comments showing up in a different color than lines of code. Since most people’s brains are pretty good at sorting colors, spacing and color-coding make it easy to focus on code or comments separately, while still keeping it easy to look at them together. That’s just like reading sheet music: the music is shown as notes in a staff, while the lyrics are printed alongside, roughly aligned but separate. You can focus on the music or the lyrics when reading sheet music .

You’ll be in great shape if you remember that good comments complement code instead of duplicating it. They pull the bare mechanics of the code into a story, making it much easier to understand the code. If you can read through the comments while ignoring the code and still feel like you understand what’s going on, then you’ve done a top-notch job.

1 Doxygen is a widely used tool that extracts strangely formatted comments from source code and generates project documentation from them. The idea is that documentation that’s right next to the code is more likely to stay up-to-date. This is true, though in my experience only for small values of more and likely . I apologize for the formatting to non-C++ programmers. I wanted to use a real example, and all of these documentation-generating tools use strange formatting on purpose—because the tool looks for the strange formatting to mark the text it needs to process.

2 They mark terms that should be typeset in a fixed-width font, like Courier. Hence “c”.