Rule 9. Write Collapsible Code

I end up spending a lot of time looking through code, trying to figure out what it’s doing. The subject might be code I’m trying to debug, some bit of code I’m thinking about calling from some code I’m writing, or some bit of code that’s calling code I’m responsible for. And frequently the thing the code is trying to do isn’t what it’s actually doing, which is what makes the exercise interesting.

At its best, reading code is just like reading any other language. You sail along through the narrative, top to bottom, eagerly following the twists and turns of the plot, and reach the end of the code with a full understanding of what it does and why.

Actually, at its easiest, you sight-read code just like you’d sight-read a single word:

int sum = 0;

Or maybe:

sum = sum + 1;

There’s no thinking or reasoning involved for these two examples—a glance at the code is enough to understand it. You can do the same thing for bigger chunks of code, if they neatly fit some common paradigm:

Color Flower::getColor() const
{
    return m_color;
}

You might even be able to sight-read a whole loop:

int sum = 0;
for (int value : values)
{
    sum += value;
}

That’s pushing things, though. As blocks of code get bigger, it becomes harder to sight-read them—or if you’re a cynical old programmer like me, it gets harder to trust your ability to sight-read them, having made the mistake of glancing at code and thinking I understood it way too many times.

When code gets too big to ...

Get The Rules of Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.