The most basic idea in this book is that programming is complicated, and that your productivity as an individual and as a team is gated on that complexity. The more complicated you make things—or let things become—the less successful you’ll be. The simpler you keep things, the more successful you’ll be—so keep things simple!

That advice holds true no matter what sort of project you’re working on, but it’s truer for some projects than others.

There are projects that are small enough and simple enough that unnecessary complexity won’t really matter. If you’re writing a hundred lines of code by yourself in an afternoon and you’re going to throw away the code when you’re done, then you can write that code just about any way you’d like and get away with it.

Once you’re on a team, even if it’s a two-person team, that’s less true. You might try to draw lines between “my code” and “your code,” with each of you deciding how code gets written on your side of the line…but this won’t work very well. Unless your two halves are extraordinarily cleanly separated and remain that way through the life of the project, you’ll be popping back and forth across the boundary routinely. Even defining the interface between the two halves gets problematic—for example, who decides how things in the interface are named, when half of the interface is on each side of the line?

There’s no good way to extend this my-side-your-side pattern to larger teams, but that doesn’t stop people from trying. For some programmers, there’s a strong appeal to making all the decisions about “your” code. It’s easy to argue that programming is a creative act, and that constraints make for less creativity. It’s easy to argue that different parts of the projects have different needs, and so should be treated differently. It’s easy to get attached to the smallest parts of your programming style, only to find yourself in a heated argument about where a curly brace goes.

All of these arguments are wrong. Not entirely wrong, but whatever small kernel of truth exists in each of them is outweighed by the reality of working on a large team on a large project. Differences in coding style add complexity, which makes everyone’s jobs harder.

Formatting Conventions

Every bit of code embodies some style and philosophy. Working your way through some bit of code that uses a foreign style or philosophy is slower and more error-prone. It’s like reading a foreign language you only mostly understand; everything is a struggle.

If you’re used to code that looks like this:

/// \struct TREE
/// \brief Binary tree of integers
/// \var TREE::l
/// Left subtree
/// \var TREE::r
/// Right subtree
/// \var TREE::n
/// Data

/// \fn sum(Tree * t)
/// \brief Return sum of all integers in the tree
/// \param t Root of tree (or subtree) to sum
/// \returns Sum of integers in tree

struct TREE { typedef TREE self; self * l; self * r; int n; };
int sum(TREE * t) { return (!t) ? 0 : t->n + sum(t->l) + sum(t->r); }

…then code like this is going to be harder to read, and vice versa:

// Integer tree node

struct STree
{
    STree *     m_leftTree;
    STree *     m_rightTree;
    int         m_data;
};

// Return sum of all integers in tree

int sumTree(STree * tree)
{
    if (!tree)
        return 0;

    return tree->m_data + 
           sumTree(tree->m_leftTree) + 
           sumTree(tree->m_rightTree);
}

I’m not making a value judgment here—in some sense, this is the same code; the only differences are naming and formatting. I’m used to programming in something like the second style, so the first style seems strange to me. Reading it requires some mental translation. If you’re used to the first style, you’d have the opposite reaction.

The problem here isn’t the coding style, it’s mixing those styles. If you mix styles—again, adding complexity—you’re going to struggle when moving between them. Trying to maintain different styles for different sections of your code is a bad idea.

Language Usage Conventions

The same is true for use of language features. If you’re used to “basic” C++ code like the previous example, then more “modern” C++ like this is going to be hard to read:

int sumTree(const Tree * tree)
{
    int sum = 0;
    visitInOrder(tree, [&sum](const Tree * tree) { sum += tree->m_data; });
    return sum;
}

If you’re used to older versions of C++, you might not even recognize this as legitimate code! There’s a lambda definition in there (it’s the part starting with [&sum] ), and lambdas weren’t added until C++ 11.

Again, I’m not making a value statement here. Lambdas can be useful, and I understand why C++’s implementation works the way it does. If lambdas are a standard part of your team’s workflow, and you all have a solid shared understanding of how and where to use them, then there’s nothing wrong with the preceding code. If you’re the lone lambda champion on the team, then the same code is a disaster. The problem here isn’t the use of language features per se—it’s mixing different expectations about which language features to use. If you’re used to one set of language features, then adjusting to a different set saps your energy. That’s especially true when those transitions are unexpected, leaving you unsure of which set of conventions is in force for some bit of code you’re looking at.

Problem-Solving Conventions

Programmers don’t run into a lot of problems that have only one solution, so we all develop our own instincts about how to solve a particular problem when writing code. That creates problems when your instincts don’t match up with those of your teammates—you’ll solve the same problem in different ways. At best, that increases cognitive load as you look at each other’s code. More likely, it results in reinventing the wheel: you all end up solving the same problem multiple times in multiple ways, because you don’t recognize that it has already been solved.

Take error handling. There are lots of ways of handling errors: some introduced by the language and its libraries, others extrapolated by teams to meet their own particular needs. Even if you limit yourself to the built-in parts of C++, you’ll find at least three distinct error-handling models, each featured at some point in the 50-year evolution of the language.

Even the definition of error itself is up for grabs! You could reasonably decide that usage mistakes are errors—after all, this is what the operating system and most libraries do. You could just as easily decide that errors should be reserved for unavoidable problems, like a missing file, not entirely avoidable usage mistakes.

At Sucker Punch , for instance, we deal with usage errors as asserts, not as errors. That’s our convention. Given the many choices about how to handle errors, we chose one, and we all stick to it.

Sticking to one convention is a challenge, not least because every library or other dependency drags you into its error-handling model. At a minimum, you need to deal with the errors the library returns—and then decide how to propagate them. If you’re dealing with really old-school C-style file handling, that leads to some unpleasant code:

string getFileAsString(string fileName)
{
    errno = 0;
    string s;
    FILE * file = fopen(fileName.c_str(), "r");
    if (file)
    {
        while (true)
        {
            int c = getc(file);
            if (c == EOF)
            {
                if (ferror(file))
                    s.clear();

                break;
            }

            s += c;
        }

        fclose(file);
    }

    return s;
}

In this 1980s-style code, errors are returned with a combination of global state and special return values. The details aren’t that important—but the relative lack of conventions here is notable. Every function has a slightly different idea of how to return errors— fopen returns nullptr on error, getc returns EOF but sets a global flag, and so on. Using this model means memorizing a bunch of arbitrary details.

Moving errors onto the objects themselves improves things slightly—and new, stronger conventions can be introduced:

bool tryGetFileAsString(string fileName, string * result)
{
    ifstream file;
    file.open(fileName.c_str(), ifstream::in);
    if (!file.good())
    {
        log(
            "failed to open file %s: %s", 
            fileName.c_str(), 
            strerror(errno));

        return false;
    }

    string s;
    while (true)
    {
        char c = file.get();
        if (c == EOF)
        {
            if (file.bad())
            {
                log(
                    "error reading file %s: %s", 
                    fileName.c_str(), 
                    strerror(errno));

                return false;
            }

            break;
        }

        s += c;
    }

    *result = s;
    return true;
}

The convention here is that functions with names starting with try might fail. They return true on success and false on failure, and any details about the failure are reported to a system error log. If you see a try -named function, you know exactly what to expect. That’s the power of conventions—they’re a shortcut to understanding, much preferable to reading through the code to figure out the details for yourself. As in this code, any library that doesn’t use the convention forces some conversion work, but that’s work only one coder has to do—the rest of the team can enjoy a consistent error-handling convention .

I’ve worked on projects that defined a richer error type, instead of returning a simple bool for success or failure :

struct Result
{
    Result(ErrorCode errorCode);
    Result(const char * format, …);

    operator bool () const
        { return m_errorCode == ErrorCode::None; }

    ErrorCode m_errorCode;
    string m_error;
};

This kind of error reporting lets code propagate errors around while still allowing detailed, contextual error information. This is a useful model for projects that deal with lots of errors, especially when combined with a naming convention like try :

Result tryGetFileAsString(string fileName, string * result)
{
    result->clear();

    ifstream file;
    file.open(fileName.c_str(), ifstream::in);
    if (!file.good())
    {
        return Result(
                    "failed to open file %s: %s", 
                    fileName.c_str(), 
                    strerror(errno));
    }

    string s;
    while (true)
    {
        int c = file.get();
        if (c == EOF)
            break;

        if (file.bad())
            return Result(
                        "error reading file %s: %s", 
                        fileName.c_str(), 
                        strerror(errno));

        s += c;
    }

    *result = s;
    return ErrorCode::None;
}

Or you could use exceptions , the third basic error-handling model of the C++ libraries:

string getFileAsString(string fileName)
{
    ifstream file;
    file.exceptions(ifstream::failbit | ifstream::badbit);
    file.open(fileName.c_str(), ifstream::in);

    string s;
    file.exceptions(ifstream::badbit);
    while (true)
    {
        int c = file.get();
        if (c == EOF)
            break;

        s += c;
    }

    return s;
}

For better or worse, this function hides the actual exceptions, which are thrown from file.open or file.get . The advantage is that the normal flow of operation isn’t cluttered with error-handling stuff; the disadvantage is that the complexity of how errors are detected and handled is hidden and scattered over multiple functions. 1

All four of these styles are viable, as are many others. You could choose any of them as your convention—well, you’re not going to use the first style, because that would be silly. But any of the other three could make sense, depending on your project.

Here’s  what doesn’t make sense—mixing different error-handling conventions in the same project. Inconsistent conventions will leave everyone on the team slightly confused at all times, and confused programmers write bugs.

I hid an example of this in the two try -named function conventions. Both conventions pass back the “actual” return value of the function through a pointer. But in the first convention, the function leaves the actual return value unchanged if it fails; in the second convention, it’s cleared in error cases.

You can make a solid argument for either option—but you can’t mix them in the same project, because that’s an obvious disaster. The same is true with mixing exceptions in amongst error codes, which is destined to end in tears.

You might also be able to argue that your program should have no error handling. That’s right, no error handling! That’s actually the approach we take for most of our game code—we don’t define errors, so there’s no error handling. Usage errors are handled with asserts. Catastrophic problems like running out of memory just halt the game. Edge cases trigger default behaviors rather than returning errors.

It’s true that we’re forced to deal with errors at the edges of our code—our networking code needs to handle packets getting dropped, for instance. But Sucker Punch programmers can go for months and months without generating or handling a single error .

Effective Teams Think Alike

Your goal as a team—not as individuals, but as a team—should be to think as one. The ideal situation would be for everyone on the team to be so in sync that each of you would write exactly the same code when presented with a particular problem. And by “exactly,” I mean exactly : same algorithm, same formatting, same names for everything.

We all know that it’s easier to read and work with your own code than it is to work with other people’s code. Any bit of code embeds countless assumptions about how code should be written. When you’re reading your own code, all of those assumptions feel natural, so you don’t notice them. When you read other people’s code, you trip over every single one of the assumptions you don’t share.

If the naming conventions don’t match your expectations, you hit a snag. Sure, you can figure it out, but it takes time and energy. If the curly braces are in the wrong place, or the code uses unfamiliar language features or does common things using more than one convention, like the constructor example earlier, same thing.

The solution is obvious. If you want to work smoothly and harmoniously as a team, align your assumptions! Use the same conventions! Stop being dumb!

The conventions themselves—where the curly brace goes and so on—rarely matter. You can have a principled discussion about curly brace placement, but there are lots of good answers to where they go. It doesn’t matter which style you choose, as long as you all choose the same style and use it consistently.

Here’s how we deal with this at Sucker Punch. We have a set of coding standards that set out pretty strict rules for everything we can think of, including:

  • How to name everything.

  • How to format code. If you’re smart, your formatting conventions will exactly match the output from one of the many code-formatting tools, which makes following the convention easy—just run the formatting tool. 2

  • How to use language features, including which to use and which to avoid.

  • Conventions for all the common problems we solve. We have a very standardized way to write a state machine, for instance, because our game code has lots of state machines.

  • Where to draw file boundaries, and how code should be ordered and grouped within those files.

  • How to represent constants in the code. It’s not enough to say that you’re going to use a #define or a const instead of embedding magic numbers in your code—what should your const be named? Where should you define it? Near the use, at the top of the source file with the other constants, or maybe in a project-wide header file?

Everyone follows these conventions, which are gently enforced during our code review process. It’s an adjustment for many of our new coders to work within strict standards like these, but it doesn’t take long for the benefits of strict adherence to the coding standards to become obvious.

At the beginning of every project, we let anyone on the coding team propose any change they’d like to the coding standards. We debate each proposed change, then vote. If a proposal wins a majority of the vote, it goes into effect for the new project. During the last round of voting, for instance, we approved the use of auto in certain circumstances, which (depending on your own proclivities) may seem horribly strict or entirely too permissive. 3

Once we’ve made all the changes to our standard, we divvy up our fairly large codebase and sweep through it like a swarm of hungry locusts, converting everything to match the new standard. This isn’t cheap, but it takes less than a week, and at the end we’ve got squeaky-clean compliance with our team conventions .

Remember our goal: that any Sucker Punch coder, faced with a particular problem, will write exactly the same solution as any other Sucker Punch coder. The closer we get to that, the closer we are to the perfect situation—where working with anyone else’s code is as easy as working with your own. If I’m looking at some bit of Sucker Punch code and I can’t tell who wrote it—or even whether I wrote it myself—then I know we’re getting close to that goal, and we’ve set ourselves up for stress-free programming. 4

1 Given the other Rules in this book—most importantly Rule 10, “Localize Complexity” —it will not surprise you to hear that C++ exceptions are not used at Sucker Punch, and it’s for this very reason. We do have a few try statements in the codebase, but only when forced to by external libraries in our toolchain.

2 We are, alas, not this smart. Our formatting conventions are…idiosyncratic.

3 Hence conventions.

4 OK, OK, not actually stress-free. But a lot less stressful.