You can’t write about programming without quoting Shakespeare, obviously. It’s sort of a cliché at this point. Nevertheless, here’s Romeo and Juliet , a quick recap: Romeo and Juliet are star-crossed teens in love, prevented by the enmity between their two families from spending a joyful life together. It ends poorly for all involved.

Act II, Scene II. Juliet bemoans the situation in the fifth-most famous quote from the play:

What’s in a name? That which we call a rose
By any other name would smell as sweet

I’ve heard similar arguments made about code, typically by colleagues frustrated by my persnickety code review attitude toward how stuff is named. Variables, functions, members, source files, class and structure names—I’ll quibble about any of them.

People will argue, typically with an eye roll, that the name doesn’t really matter, that what matters is the thing named. The true meaning of the variable (or function, or class, whatever) can only be determined by looking at the code. The truth of a variable is what it represents—how it’s set, how it’s used, not what it’s named. The functionality doesn’t change if the name is changed.

So, they declare, just choose something easy to type and get on with coding.

These people are wrong.

The name of a thing is the first and most important documentation you have. It’s inescapable. It’s always there. Whenever you see any sort of reference to the thing, it’s by its name. That continual presence is a glorious opportunity to tell the reader what the thing is, every single time they see it.

This sort of opportunity should never be squandered.

Your goal when choosing the name for something is simple—the name should encapsulate what’s important about the thing, and guide the reader in how to think about it. If you’re naming a variable, the name should immediately tell the reader what the variable represents. If you’re naming a function, the name should tell the reader what the function does.

Sounds simple, right? So how do things go sideways? As many ways as there are stars in the sky, actually, but here are a few common failure modes.

Don’t Optimize for Minimal Keystrokes

The first way things go sideways is overly curt names. Remember that code is read much more often than it’s written. It’s easy when you’re writing code to forget this and optimize in favor of names that are easy to type, instead of spending a bit of extra effort to write code that’s easy to read.

In extremis , this leads to super short variable names. The older the code is, the more likely you’ll see this style. Or, alternatively, if you run into work done by a truly ancient programmer—someone who started programming in the ’60s or ’70s, say—then you’re more likely to see one-letter and two-letter names. 1

I think of this as Numerical Recipes code. 2 I’m a big fan of Numerical Recipes , but the coding style is pretty opaque. To paraphrase:

void cp(
    int n, 
    float rr[], 
    float ii[], 
    float xr, 
    float xi, 
    float * yr, 
    float * yi)
{
    float rn = 1.0f, in = 0.0f;
    *yr = 0.0f;
    *yi = 0.0f;
    for (int i = 0; i <= n; ++i)
    {
        *yr += rr[i] * rn - ii[i] * in;
        *yi += ii[i] * rn + rr[i] * in;
        float rn2 = rn * xr - in * xi;
        in = in * xr + rn * xi;
        rn = rn2;
    }
}

Not immediately obvious what’s going on, right? You could puzzle it out—the code evaluates a polynomial over complex numbers—but it’s some work. Things are a lot easier with more appropriate names :

void evaluateComplexPolynomial(
    int degree, 
    float realCoeffs[], 
    float imagCoeffs[], 
    float realX, 
    float imagX, 
    float * realY, 
    float * imagY)
{
    float realXN = 1.0f, imagXN = 0.0f;
    *realY = 0.0f;
    *imagY = 0.0f;
    for (int n = 0; n <= degree; ++n)
    {
        *realY += realCoeffs[n] * realXN - imagCoeffs[n] * imagXN;
        *imagY += imagCoeffs[n] * realXN + realCoeffs[n] * imagXN;
        float realTemp = realXN * realX - imagXN * imagX;
        imagXN = imagXN * realX + realXN * imagX;
        realXN = realTemp;
    }
}

And obviously this particular bit of code is simpler if you have a data type for complex numbers:

void evaluateComplexPolynomial(
    vector<complex<float>> & terms,
    complex<float> x,
    complex<float> * y)
{
    complex<float> xN = { 1.0f, 0.0f };
    *y = { 0.0f, 0.0f };
    for (const complex<float> & term : terms)
    {
        *y += xN * term;
        xN *= x;
    }
}

Now the structure of the algorithm is clear, if you remember how complex numbers work . You multiply each term by the domain value x taken to the N th power, accumulating the results in the range variable y .

Don’t Mix and Match Conventions

The second way names go wrong is inconsistency. When code doesn’t use consistent rules about how things are named, it’s easy for the reader to get confused.

For most projects, some amount of inconsistency is hard to avoid. If you use any external libraries, then you’ve got trouble—unless all of your dependencies share the same naming rules, and you’re willing to work within those rules yourself. Say you’re writing a native Windows app, and you’re willing to adopt Microsoft’s naming conventions—then your code can be consistent. Or you’re going to use the C++ standard template libraries and can live with their conventions: still consistent. Otherwise, there will be visible seams as things named with competing conventions are mixed.

Imagine that you’ve got a vector class that pre-allocates storage for a fixed number of elements. That’s useful and not something the C++ standard library provides. Imagine your project has a simple naming scheme for object methods—camel case, starting with a verb. Leaving out a bunch of details, your class looks like this :

template <class ELEM, int MAX_COUNT = 8>
class FixedVector
{
public:

    FixedVector() :
        m_count(0)
        { ; }

    void append(const ELEM & elem)
        {
            assert(!isFull());
            (void) new (&m_elements[m_count++]) ELEM(elem);
        }
    void empty()
        {
            while (m_count > 0)
            {
                m_elements[--m_count].~ELEM();
            }
        }
    int getCount() const
        { return m_count; }
    bool isEmpty() const
        { return m_count == 0; }
    bool isFull() const
        { return m_count >= MAX_COUNT; }

protected:

    int m_count;
    union
    {
        ELEM m_elements[0];
        char m_storage[sizeof(ELEM) * MAX_COUNT];
    };
};

This is pretty straightforward. 3 The append method adds a new element, the empty method empties out the whole array, and you’ve got some accessors to check the current number of elements in the vector. But if you write code that mixes this FixedVector class with a standard C++ container, things aren’t so rosy:

void reverseToFixedVector(
    vector<int> * source, 
    FixedVector<int, 8> * dest)
{
    dest->empty();
    while (!source->empty())
    {
        if (dest->isFull())
            break;

        dest->append(source->back());
        source->pop_back();
    }
}

Here you have two consecutive lines that call an empty method on a vector, but those two calls do completely different things. The first call empties the destination vector; the second call checks to see whether the source vector is empty. It’s pretty easy to see how this would cause confusion!

Obviously you could adopt Standard Template Library (STL) conventions for the FixedVector class—you could rename it fixed_vector , and use STL-style names for all of its methods—but that just moves the line of confusion elsewhere in your project. Now you’re not just asking your programmers to adapt to and use a foreign set of naming conventions—you’re asking them to write code with those conventions as well. That’s a much bigger undertaking .

It’s easy to underestimate the cognitive load of mixing conventions like this. There’s a real cost to switching back and forth, constantly reinterpreting what you’re reading in terms of which set of conventions it must be using. In this example, that means popping back and forth in the code to figure out which variable has which type, and therefore which set of conventions it uses. Assuming that you know which conventions are used by which type, of course!

At Sucker Punch we avoided the specific problem of inconsistency between our conventions and the standard C++ container conventions by writing our own version of all the container classes instead of using the STL versions. That’s a pretty extreme solution, but it does eliminate a lot of cognitive strain—the container classes work just like all the other code we write, so single-stepping into a container class’s method doesn’t drop you into a foreign landscape. Like, say, the STL’s jungle of macros and truly unhinged template magic. Not to judge, but still.

Even so, we’re not entirely free of foreign conventions, because we use code we didn’t write, like the PlayStation platform libraries. For most projects, some degree of mixed conventions is inevitable. The key is to minimize the mixing where possible. Ring fence the foreign bodies if you can, in hopes that their conventions won’t leak out into the code everyone deals with all the time.

Don’t Shoot Yourself in the Foot

Avoid self-inflicted wounds—if the programmers on your team aren’t using consistent naming conventions, you’re all creating entirely avoidable problems for yourselves. A jumble of conventions makes even straightforward code a challenge to sort out:

int split(int min, int max, int index, int count)
{
    return min + (max - min) * index / count;
}

void split(int x0, int x1, int y0, int y1, int & r0, int & r1)
{
    r0 = split(x0, x1, y0, y1);
    r1 = split(x0, x1, y0 + 1, y1);
}

void layoutWindows(vector<HWND> ww, LPRECT rc)
{
    int w = ww.size();
    int rowCount = int(sqrtf(float(w - 1))) + 1;
    int extra = rowCount * rowCount  - w;
    int r = 0, c = 0;
    HWND hWndPrev = HWND_TOP;
    for (HWND theWindow : ww)
    {
        int cols = (r < extra) ? rowCount - 1 : rowCount;
        int x0, x1, y0, y1;
        split(rc->left, rc->right, c, cols, x0, x1);
        split(rc->top, rc->bottom, r, rowCount, y0, y1);
        SetWindowPos(
            theWindow, 
            hWndPrev, 
            x0, 
            y0, 
            x1 – x0, 
            y1 – y0, 
            SWP_NOZORDER);
        hWndPrev = theWindow;
        if (++c >= cols)
        {
            c = 0;
            ++r;
        }
    }
}

I feel a little queasy right now. That was rough for me to type; I’m taking one for the team here.

The algorithm isn’t that complicated—I’m just arranging windows to fill a target rectangle by dividing them into columns and rows, keeping roughly the same aspect ratio as the target rectangle. But I’ve made it unnecessarily hard to figure out what’s going on with the naming choices.

The most obvious problem is the jumble of three or four different naming styles, which is bad enough. But there’s another issue that pops up even in more consistently named code—the name of something changing as it’s passed into a function. The first time I call split , I pass x0 and x1 as the last two arguments. They’ll receive the right and left sides of the window’s new rectangle. Inside the split function, though, x0 and x1 mean something completely different.

That’s a problem. If you’re single-stepping through LayoutWindows , you’ve got a mental model of what x0 and x1 are. If you single-step into split , you still see x0 and x1 —but now they mean something completely different. This function is using x and y as generic variable names, just like in algebra class. They’re not connected in any way with a coordinate system, like x and y are in the LayoutWindows function. Algebra in one function, Cartesian coordinates in the next—that’s cognitive load, which slows you down and creates mistakes.

Some amount of this renaming in function calls is unavoidable. Function arguments are often the result of expressions, not just passing another variable. In this example the first two arguments to split are rc->left and rc->right , which can’t be the names for those concepts inside the split function. You’ll have to create variable names—but if you’re smart, those variable names will be left and right , which makes it easier to track what’s what as you single-step into the function.

Here’s the same function reorganized a bit to make it more consistent and readable:

int divideRange(int min, int max, int index, int count)
{
    return min + (max – min) * index / count;
}

void layoutWindows(vector<HWND> windows, LPRECT rect)
{
    int windowCount = windows.size();
    int rowCount = int(sqrtf(float(windowCount - 1))) + 1;
    int shortRowCount = rowCount * rowCount - windowCount;

    HWND lastWindow = HWND_TOP;
    int rowIndex = 0, colIndex = 0;

    for (HWND window : windows)
    {
        int colCount = (rowIndex < shortRowCount) ? 
                            rowCount - 1 : 
                            rowCount;

        int left = divideRange(
                        rect->left, 
                        rect->right, 
                        colIndex, 
                        colCount);
        int right = divideRange(
                        rect->left, 
                        rect->right, 
                        colIndex + 1, 
                        colCount);
        int top = divideRange(
                        rect->top, 
                        rect->bottom, 
                        rowIndex, 
                        rowCount);
        int bottom = divideRange(
                        rect->top, 
                        rect->bottom, 
                        rowIndex + 1, 
                        rowCount);

        SetWindowPos(
            window,
            lastWindow,
            left,
            top,
            right - left,
            bottom - top,
            SWP_NOACTIVATE);

        lastWindow = window;
        if (++colIndex >= colCount)
        {
            colIndex = 0;
            ++rowIndex;
        }
    }
}

Still the same algorithm, but much easier to understand. Consistent naming patterns make it easier to track what’s going on. It’s easier to identify the concept represented by a variable solely from its name, without inspecting the code to infer its meaning—you may not know everything about a variable named rowIndex , but you can be pretty sure it’s the index of a row. Which row and of what is not as clear, but knowing it’s a row index is a big head start .

Consistently naming indexes and counts has some positive side effects. When you step into the divideRange function, it also uses index and count as argument names. It’s easy to mentally translate the colIndex and colCount variables in layoutWindows to the index and count arguments of divideRange . I’ve minimized the cognitive load, especially compared to the x0 / x1 mess of my first version of this function.

This is common. If you have a consistent set of rules for naming things, then as you pass between different functions, or different sections of the codebase, similar things will have similar names. Identical things will usually have identical names. As you single-step through code, or try to understand how different bits of code interact with each other, you don’t have to juggle a bunch of names for a single thing. There’s only one name—or only a small number of obviously and closely related names, like the index + count example earlier .

Don’t Make Me Think

Actually , you can go further with rules to create consistency.

The key to consistency is for everything to be as mechanical as possible . If your team’s conventions for how things are named require judgment calls or careful thought, then they won’t work. Different programmers will make different judgment calls, and everyone’s names will be different.

You’d much rather be in a happy spot where everyone just naturally chooses the same names for the same things, because that makes working with everyone’s code much easier. And the easiest way to create this level of consistency is to have mechanical rules that everyone follows.

The Sucker Punch rules for variable naming are especially mechanical. I haven’t used them for the examples in this book, mostly in the interest of approachability. Our rules work well for us, but that’s because we all use them constantly. They’re a little strange-looking if you’re seeing them for the first time.

Instead , I’ve used gentler conventions for this book’s examples—if I’ve got a class representing a character, the class is named Character and a variable holding a character is typically named character , while a vector full of characters would be named characters . 4 Simple conventions chosen for readability, but consistently used.

The Sucker Punch codebase is similar in spirit, just with a more thorough set of rules and a little bit more terseness. We use a variant of Microsoft’s Hungarian standard for variable naming. This is…divisive. Not so much with Sucker Punch programmers, who adapt pretty quickly, but outside of the Microsoft ecosystem, the Hungarian naming standard is commonly a target of derision. 5

The core idea of the Hungarian standard is that the type (or sometimes usage) of a variable mechanically determines all or part of the variable’s name. If you have an index into an array of factions, then that variable is named iFaction . If you have a vector of pointers to characters, then the variable is named vpCharacter .

In many cases, that’s where the story stops. The variable name is entirely mechanical, and as a result everyone uses exactly the same name for the variable. That’s what we’re hoping for!

If you have multiple variables with the same type, you tack a qualifier onto the end of the variable name. If you have two character pointers, they might be called pCharacter and pCharacterOther . This does introduce judgment calls, but the conventions we have about common qualifier patterns limit the inconsistency introduced.

The important thing isn’t the details of our naming conventions—it’s that we have strict conventions, that they’re as mechanical as we can make them, and that they’re both well-documented and enforced. That puts us in a happy place where everyone chooses the same names for the same things, and working with someone else’s code feels like working with your own .

Figure out which of your own project conventions you can make more mechanical and do it. You’ll reap the benefits for years to come.

1 I’m of an age where my first programming language was Applesoft Basic, which allowed long variable names but only paid attention to the first two characters. You read that right; JUDGE$ and JUROR$ are aliases for the same string variable. Good times. My Basic variables were all one or two characters, as in the coding example to follow.

2 Numerical Recipes is a classic book explaining all sorts of algorithms for math and science. The Sucker Punch codebase is littered with ideas adapted from it. 10/10, would recommend. William H. Press et al., Numerical Recipes: The Art of Scientific Computing , 3rd ed. (Cambridge University Press, 2007).

3 Well, a zero-sized array isn’t straightforward. Support is compiler-dependent; the compiler I use supports them but is grouchy about it. I could write the code without a zero-sized array, but it makes things easier to read and understand, so there you go.

4 Unsurprisingly, the class would be implemented in files named character.h and character.cpp .

5 I think the negativity misconstrues the advantages of the Hungarian standard. Originally, using it was a workaround to the lack of type-safe linking in early C compilers. Embedding type names into variable and function names added a degree of type safety, if only by convention. That’s unimportant at this point, but it’s the center of most of the derision. There’s also criticism that code using the convention is hard to read, but that’s like saying Icelandic is hard to read—sure, if you don’t speak it! The real value of the Hungarian standard for us now is that following its rules lets us all naturally create the same names for things, and that leads to an easier-to-work-with codebase.