O'Reilly logo

The Art of Readable Code by Trevor Foucher, Dustin Boswell

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Put Yourself in the Reader’s Shoes

A general technique we use in this book is to imagine what your code looks like to an outsider—someone who isn’t as intimately familiar with your project as you are. This technique is especially useful to help you recognize what needs commenting.

Anticipating Likely Questions

image with no caption

When someone else reads your code, there are parts likely to make them think, Huh? What’s this all about? Your job is to comment those parts.

For example, take a look at the definition of Clear():

struct Recorder {
    vector<float> data;
    ...
    void Clear() {
        vector<float>().swap(data);  // Huh? Why not just data.clear()?
    }
};

When most C++ programmers see this code, they think, Why didn’t he just do data.clear() instead of swapping with an empty vector? Well, it turns out that this is the only way to force a vector to truly relinquish its memory to the memory allocator. It’s a C++ detail that isn’t well known. The bottom line is that it should be commented:

// Force vector to relinquish its memory (look up "STL swap trick")
vector<float>().swap(data);

Advertising Likely Pitfalls

image with no caption

When documenting a function or class, a good question to ask yourself is, What is surprising about this code? How might it be misused? Basically, you want to “think ahead” and anticipate the problems that people might ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required