That title seems optimistic, doesn’t it? What does it even mean?

Some failure cases are unavoidable, right? If I try to open a file, that file might not exist, or it might be locked by some other user. No interface-design cleverness can avoid the possibility of failing to open the file. So that can’t be it. This must be more about eliminating the failures that actually are avoidable, not intrinsic to file operations—perhaps usage mistakes, like writing to a file after you’ve closed the handle to that file, or calling methods on an object before you’ve fully initialized it.

Maybe I could design systems that make it impossible to make usage mistakes, but that doesn’t sound easy. And it isn’t. It’s pretty hard to design a system that’s impossible to misuse. If you expose a feature to users, they’ll find a bizarre way to use it that eventually causes everything to explode, like building a functioning 8-bit processor entirely out of Minecraft blocks. 1

And if you expose a feature to other programmers on your team—they will misuse it. The misuse might be intentional, a desperate attempt to get something working—say, closing a file handle after calling the filesystem shutdown routine because that’s the only way to avoid an unwanted callback. More likely it will be entirely unintentional, a misinterpretation of how your interface expects to be called.

The key question to ask yourself about your design is: “How hard am I making it for users of this feature or interface to shoot themselves in the foot?”

The proper answer, of course, is “Very hard,” but too often we create features or interfaces that make inadvertent usage easy.

And if it’s easy to misuse a feature or interface, then mistakes are inevitable. In some sense, mistakes are designed into that feature or interface. What we’d like to do is to design mistakes out, rather than designing them in. But first let’s look at some examples of functions that have failures designed in.

A Function That Makes It Easy to Shoot Myself in the Foot

Every C programmer knows at least one example of a function that’s easy to get wrong— printf . There’s a fundamental problem with how printf is designed—it expects the format string it’s given to match the argument types passed, with unspecified mayhem occurring if the two don’t agree.

This code works because the types agree :

void showAuthorRoyalties(const char * authorName, double amount)
{
    printf("%s is due $%.2f this quarter.\n", authorName, amount);
}

But if we tweak the format string, things fall over:

void showAuthorRoyalties(const char * authorName, double amount)
{
    printf("remit $%.2f to %s this quarter.\n", authorName, amount);
}

Roughly speaking, printf tries to interpret authorName (which is a string) as a float (uh oh). That’s going to have unpredictable results. Not a crash, probably—since all 2 64 -bit combinations can be interpreted as doubles, something will get formatted, even if it’s “NaN.” Next, though, printf interprets amount (which is a double) as a string (uh oh) and this is very likely to crash.

Actually, this isn’t what happens when I compile and run the preceding code. Mismatching arguments like this is such an easy mistake to make that modern C compilers have hacked in an extra set of checks for printf . When I try to compile the broken example, I get compile errors (!) for both arguments. If the format string to printf is a constant, the compiler can (and does) check for type agreement.

This hack sort of proves my point—the design of printf is so bad that the compiler has to include special checks to hide the problem. Those special checks won’t happen for any of the code you’re writing, obviously. If you roll your own formatting function using a printf -style format string, the compiler is not going to check for type agreement. 2

Shooting Myself in the Foot via a Ricochet

To actually get the crash, I sidestep the compiler’s type-agreement hack:

void showAuthorRoyalties(const char * authorName, double amount)
{
    printf(
        getLocalizedMessage(MessageID::RoyaltyFormat), 
        authorName, 
        amount);
}

Instead of specifying a format string directly, I’m pulling it from a list. Our games get translated into lots of languages, so any user-visible string is going to come from a database of localized strings. The compiler has no way of knowing what the string is, so it can’t check type agreement like it does for a literal string.

The net result is a disaster—a bad idea wrapped inside a worse one. I start with the type shakiness of printf , then make it worse by entirely separating the format string from its use while keeping the hidden dependence on parameter order. Inevitably, some poor translator is going to swap the order of the two parameters in the course of translating that line due to expected word ordering in their language, 3 and our code will crash.

Perhaps we can forgive printf its inadequacies, given that its design dates back to the beginning of time. 4 But requiring separate arguments to match in some way is widespread, despite being a bad idea. You might write a routine that expects two array-valued arguments to have the same size:

void showAuthorRoyalties(
    const vector<string> & titles, 
    const vector<double> & royalties)
{
    assert(titles.size() == royalties.size());

    for (int index = 0; index < titles.size(); ++index)
    {
        printf("%s,%f\n", titles[index].c_str(), royalties[index]);
    }
}

You could also include arguments whose interpretation depends on another argument: say, flagging identity matrices in a coordinate-space conversion function in an (arguably misguided) attempt to avoid the cost of a matrix inversion and a couple of matrix multiplications:

Point convertCoordinateSystem(
    const Point & point, 
    bool isFromIdentity, 
    const Matrix & fromMatrix, 
    bool isToIdentity,
    const Matrix & toMatrix)
{
    assert(!isFromIdentity || fromMatrix.isZero());
    assert(!isToIdentity || toMatrix.isZero());

    Point convertedPoint = point;
    if (!isFromIdentity)
        convertedPoint *= fromMatrix;
    if (!isToIdentity)
        convertedPoint *= Invert(toMatrix);

    return convertedPoint;
}

At best, you’ll detect these kinds of problems when you run the code—they’ll sail right through compilation .

When you detect a problem, the alternatives aren’t great. If you return an error for mismatched arguments, then you’re stuck writing error-handling code in the caller. Writing error-handling code to account for a mistake you made in calling the function is a sign that something is seriously wrong.

Alternatively, you could add an assert that the arguments match. Depending on how you use asserts, the effect of this could range from an immediate hard crash to a message you can ignore at your own risk. No point along that spectrum is pleasant .

Enlisting the Compiler’s Aid to Avoid Shooting My Foot

It would be better to design the interface to make incorrect usage impossible—or at least to make the compiler reject it. You could combine parallel arrays to eliminate the possibility of mismatched lengths:

void showAuthorRoyalties(const vector<TitleInfo> & titleInfos)
{
    for (const TitleInfo & titleInfo : titleInfos)
    {
        printf("%s,%f\n", titleInfo.m_title.c_str(), titleInfo.m_royalty);
    }
}

You could also collapse related arguments into a single argument:

Point convertCoordinateSystem(
    const Point & point, 
    const Matrix & fromMatrix, 
    const Matrix & toMatrix)
{
    Point convertedPoint = point;
    if (!fromMatrix.isIdentity())
        convertedPoint *= fromMatrix;
    if (!toMatrix.isIdentity())
        convertedPoint *= Invert(toMatrix);

    return convertedPoint;
}

The localized printf nightmare is trickier to fix. If you want to both make things type safe and also give correct results when arguments are reordered during translation, the simple solution of using strings for all the arguments to the formatting function isn’t quite enough.

If you create helper functions that format a single argument, returning a field name and the formatted argument, you can solve both problems:

void showAuthorRoyalties(const char * authorName, double amount)
{
    // Eg "{AuthorName} is due {Amount} this quarter."

    printMessage(
        MessageID::RoyaltyFormat,
        formatStringField("AuthorName", authorName),
        formatCurrencyField("Amount", "#.##", amount));
}

Now you can at least detect any lack of agreement between the localized format string and the arguments you’re passing, though unfortunately not at compile time. The format string can specify the arguments in whatever order makes sense for the target language and printMessage will sort things out. If the format string names a field you’re not providing or doesn’t name a field you do provide, that can be logged at runtime. Better yet, the mismatch could be flagged in whatever tool the localization team uses to do localization, so that they can fix it before the code even runs .

Timing Is Everything

A key point in creating failure-proof interfaces is to detect usage mistakes as early as possible.

In the worst case, the mistaken usage isn’t detected at all—the feature just generates incorrect results. It relies on the caller to realize their mistake and sort things out. They won’t; they’ll just wonder how their foot got full of holes.

If a mistake is detected when the code runs—well, that’s not great, though it’s better than continuing blithely on without noting the problem. Ideally the mistake is reported in some unmissable way.

It would be better if the compiler detected the mistake instead. It’s hard to miss code that fails to compile.

Or best of all, the design of the system might make it impossible to express the mistaken idea at all!

A More Complicated Example

Another place where failure is often designed in rather than out is the construction of complex objects.

Here’s an example . At Sucker Punch, we write a lot of code that draws visualizations in our game world to help with debugging. For example, we have code that shows a wireframe outline of the places characters are allowed to walk. We also have code to draw little markers over the heads of NPCs that are currently aware of the player, meaning that the AI system is modeling that the NPC knows exactly where the player is. We have code that draws little numeric scores above the various places an enemy swordsman is thinking about moving to in a fight.

Debug drawing like this is more complicated than it sounds. Our debug-rendering tech supports 30 separate drawing options, all expressed on a debug-drawing context object. The 30 options determine how the program will turn simple drawing calls—like a call to draw a triangle when given three points—into actual drawing primitives. What coordinate space are those points in? Should the triangle be drawn as a wireframe or opaque? Should the triangle be visible if it’s behind a wall? And so on, for another 27 options.

We could pass 30 options to a constructor, but that’s pretty unwieldy. If we did that for an adapted and simplified version of our actual debug-drawing parameter structure, we might end up with something like this :

struct Params
{
    Params(
        const Matrix & matrix,
        const Sphere & sphereBounds,
        ViewKind viewKind,
        DrawStyle drawStyle,
        TimeStyle timeStyle,
        const Time & timeExpires,
        string tagName,
        const OffsetPolys & offsetPolys,
        const LineWidth & lineWidth,
        const CustomView & customView,
        const BufferStrategy & bufferStrategy,
        const XRay & xRay,
        const HitTestContext * hitTestContext,
        bool exclude,
        bool pulse,
        bool faceCamera);
};

All of these options are used by some bit of Sucker Punch code, but most callers specify only one or two options. The default choices are usually correct. We do most of our debug drawing in the same 3D coordinate space we use for the game itself, for instance. If we wanted to draw a simple sphere above a character’s head, as in our example showing which NPCs are aware of the player, we might write something like this :

void markCharacterPosition(const Character * character)
{
    Params params(
        Matrix(Identity),
        Sphere(),
        ViewKind::World,
        DrawStyle::Wireframe,
        TimeStyle::Update,
        Time(),
        string(),
        OffsetPolys(),
        LineWidth(),
        CustomView(),
        BufferStrategy(),
        XRay(),
        nullptr,
        false,
        false,
        false);

    params.drawSphere(
        character->getPosition() + Vector(0.0, 0.0, 2.0),
        0.015,
        Color(Red));
}

This is pretty bad. It’s an inconvenient design to use, and it has too many inherent failure points. You’re never going to remember the order of 16 arguments, leaving you at the mercy of your IDE to remind you of what goes where. For arguments with unique types, the compiler will likely bail you out if you guess wrong, but good luck keeping track of which of the four random Boolean arguments at the end of the list does what. If you’re just reading through markCharacterPosition , they’re a total mystery.

And keep your fingers crossed that you’ll never add or remove an argument from the constructor. A quick review of the Sucker Punch codebase shows 850 or so places where we build debug-rendering parameters. I wouldn’t want to be the person who removed a parameter from each of them!

Here’s the thing about functions with lots of parameters—they’re unwieldy to use, and the unwieldiness grows over time. That’s because you’re fighting a positive feedback loop. The function that’s most likely to grow another parameter is the one that already has a bunch of parameters. If a function takes eight arguments, you’ve got pretty strong evidence that at some point you’ll decide to add a ninth. The worst offenders tend to get even worse. It’s best to plan an escape route when you feel like a function is starting to have too many parameters.

The most common workaround for parameter-heavy constructors is to break the construction process up into multiple calls. The actual constructor fills in default values, then you call construction-phase-only methods to fill in any nondefault values. When you’re done, you cap things off with some sort of commit call.

Let’s imagine we want the character marker to be visible through walls, but dimmed down by 50%. A phased constructor approach might look like this:

void markCharacterPosition(const Character * character)
{
    Params params;
    params.setXRay(0.5);
    params.commit();

    params.drawSphere(
        character->getPosition() + Vector(0.0, 0.0, 2.0),
        0.015,
        Color(Red));
}

This is much better than the 16-argument version, but we’ve designed in a new failure point—we’ve introduced ordering requirements. One set of methods, like setXRay , is called while we’re constructing the params. The other set of methods, like drawSphere , is called after we’ve fully constructed the params. We haven’t defined what happens if we call them out of this expected order—calling setXRay after commit , or calling drawSphere before commit —so the editor and compiler can’t help us. The mistake won’t be detected until runtime, in this case probably as an assert inside setXRay or drawSphere .

Catching mistakes that late isn’t optimal. Better than not catching them at all, but we’d like to catch them earlier, or design away the possibility.

You might use conventions to help people avoid ordering mistakes. Your team could define a set of conventions about how to build multiphase constructors—say, that there are never any arguments to the constructor, there’s always a commit method, and asserts are used to flag usage mistakes. If you see a commit method, then you recognize the pattern and know how to build and use the object. That’s better than no conventions, of course, but it’s not the best we can do.

In the ideal case, we wouldn’t rely on conventions; we’d get the compiler to enforce correct usage. It’s better to make an incorrect usage impossible, not just avoidable .

Making Ordering Mistakes Impossible

One way to do this is to divide the two phases into separate objects—build the parameters, then draw using those parameters. To spice things up, let’s add a couple of extra parameters. We’ll draw a solid version of the sphere instead of the default wireframe, and pulse the sphere’s size a bit to make it more visible. Separating the phases into objects, that looks like this:

void markCharacterPosition(const Character * character)
{
    Params params;
    params.setXRay(0.5);
    params.setDrawStyle(DrawStyle::Solid);
    params.setPulse(true);

    Draw draw(params);
    draw.drawSphere(
        character->getPosition() + Vector(0.0, 0.0, 2.0),
        0.015,
        Color(Red));
}

With this structure, ordering is implied. You need a Params object to create a Draw object, so it’s natural to create it first.

There’s an idiomatic C++ trick you can use to make things a little bit more concise. If you return a reference to the object itself from the set functions, you can chain the set calls together. You might want to avert your eyes if you’re squeamish:

void markCharacterPosition(const Character * character)
{
    const Params params = Params()
                          .setXRay(0.5)
                          .setDrawStyle(DrawStyle::Solid)
                          .setPulse(true);

    Draw draw(params);
    draw.drawSphere(
        character->getPosition() + Vector(0.0, 0.0, 2.0),
        0.015,
        Color(Red));
}

Unless you’re used to this idiom, that doesn’t look like C++ code, which is not a plus. If you’re a believer in the Principle of Least Astonishment—in this context, the belief that the least surprising expression of an algorithm is its best expression—then it isn’t great to drop in some code that happens to be legal but looks really weird.

There is one big plus here, though. Since all the monkeying about with Params happens in our method chaining, we can make the Params object constant with C++’s const keyword. That means the compiler will stop us from mucking with it once it’s built. This fixes a lingering bit of ambiguity—it isn’t clear what happens if you alter a Params object after constructing a Draw object from it. Making the Params object const makes this moot.

Still, though, defining two objects is a pain. Separating the classes makes it clearer to some Sucker Puncher writing debug visualization code that they shouldn’t call the set functions after the draw functions…but it would be even better if it were truly impossible, not just clear. Given how I’ve created the preceding code, we can do exactly that:

void markCharacterPosition(const Character * character)
{
    Draw draw = Params()
                .setXRay(0.5)
                .setDrawStyle(DrawStyle::Solid)
                .setPulse(true);

    draw.drawSphere(
        character->getPosition() + Vector(0.0, 0.0, 2.0),
        0.015,
        Color(Red));
}

Now the weird “method chain” idiom makes more sense! We don’t expose the Params object to the rest of the code at all. It only exists long enough to construct the Draw object, so there’s no copy of it for us to accidentally reference. This is actually pretty tight code—written like this, we’ve designed out failure .

Like all weird little idioms, this one is best when it’s widely used on your project. Then it doesn’t seem weird. Everyone on your team recognizes the idiom when it’s used, and you don’t violate the Principle of Least Astonishment. If your team isn’t already using this idiom, then don’t introduce it to solve one object-construction problem. If I saw this in a code review, I’d reject it on principle, because we don’t use the method chaining idiom at Sucker Punch, but I can easily imagine another instance of Sucker Punch somewhere in the multiverse where method chaining is the standard way to solve problems like this .

Using Templates Instead of Method Chaining

The weird little idiom we do accept at Sucker Punch is using C++ templates to do this sort of type-safe optional argument stuff. This isn’t the only problem we have that involves a big bucket of parameters, only a few of which are used by most callers, so we’ve established conventions about how to handle those problems.

The code we’d actually write for a Params object might look like this:

void markCharacterPosition(const Character * character)
{
    Draw draw(XRay(0.5), DrawStyle::Solid, Pulse());

    draw.drawSphere(
        character->getPosition() + Vector(0.0, 0.0, 2.0),
        0.015,
        Color(Red));
}

This isn’t better or worse than the method-chaining model, just different. For us, it’s better because it’s the idiom we use; to a team that uses method chaining, it would seem opaque and weird. In the end, though, any idiom that eliminates usage errors—that stops a programmer from shooting themself in the foot—is a big step up from an idiom that relies on users to get all the details right on their own.

Coordinated Control of State

This Rule has looked at two common examples so far—argument matching and complicated constructors—and how we can design interfaces to them to eliminate usage errors. Here’s a third example that pops up repeatedly in Sucker Punch games: coordinating all the code that wants to manage the state of our game’s characters.

Let’s say that we’re deciding whether a character is going to react to some damaging event, like getting hit with an arrow. Generally, if a character is hit by an arrow, they need to react. But not always! If the game has launched into a scripted cut scene with the player walking up to talk to an NPC, then we’d rather just ignore a stray arrow flying in and hitting the player. It might look dumb, but it’s better than the alternative—inflicting damage on the player when they’re not in control is a cardinal sin of game design. Cut scenes are also pretty fragile, so having the player take damage could throw off everything else that’s supposed to happen in the cut scene. Better just to have the arrow bounce off.

The tricky bit is that there are lots of reasons why a character might be temporarily invulnerable. It’s not just cut scenes! The character might have just chugged an invulnerability potion. We might make them briefly invulnerable after getting hit by an arrow to avoid animation issues. Maybe it’s convenient to make the player invulnerable while we’re testing new attacks, so we add a debug menu option for player invulnerability. We end up with dozens of places where characters are temporarily marked invulnerable.

The most obvious approach is to focus on the character’s invulnerability. At any point, the character is either invulnerable or not—why not just expose that? That seems simple:

struct Character
{
    void setInvulnerable(bool invulnerable);
    bool isInvulnerable() const;
};

Then we might make the player invulnerable for cut scenes like this:

void playCelebrationCutScene()
{
    Character * player = getPlayer();
    player->setInvulnerable(true);
    playCutScene("where's chewie's medal.cut");
    player->setInvulnerable(false);
}

This works, but only as long as only one bit of code at a time is monkeying with the player’s invulnerability. We probably have similar code for the invulnerability potion: 5

void chugInvulnerabilityPotion()
{
    Character * player = getPlayer();
    player->setInvulnerable(true);
    sleepUntil(now() + 5.0);
    player->setInvulnerable(false);
}

It’s easy for these two bits of code to get tangled up, because the design makes usage errors easy. If the player pops the cork on an invulnerability potion during a cut scene, then we’ve got trouble. The cut scene starts and makes the player invulnerable via setInvulnerable , then the potion is chugged and calls setInvulnerable again. This doesn’t have any effect since the player is already invulnerable. Five seconds later, the potion wears off and calls setInvulnera⁠ble​(false) …while the cut scene is still rolling. Not good.

If we were going to generalize based on one example, we might try to fix the problem like this:

void playCelebrationCutScene()
{
    Character * player = getPlayer();
    bool wasInvulnerable = player->isInvulnerable();
    player->setInvulnerable(true);
    playCutScene("where's chewie's medal.cut");
    player->setInvulnerable(wasInvulnerable);
}

void chugInvulnerabilityPotion()
{
    Character * player = getPlayer();
    bool wasInvulnerable = player->isInvulnerable();
    player->setInvulnerable(true);
    sleepUntil(now() + 5.0);
    player->setInvulnerable(wasInvulnerable);
}

This code tries to restore the original state of the flag to avoid entanglements. This sort of works—Sucker Punch has shipped games with solutions like this—but it falls apart once we don’t have strict nesting. That could happen if the player chugs the invulnerability potion right before the cut scene starts, for instance, leaving the potion to wear off after the cut scene starts.

So how to eliminate these usage errors? Well, we could think about separating the various bits of invulnerability code. If we maintained separate invulnerability flags for each bit of interested code, then those bits of code wouldn’t get entangled:

void playCelebrationCutScene()
{
    Character * player = getPlayer();
    player->setInvulnerable(InvulnerabilityReason::CutScene, true);
    playCutScene("it's anti-fur bias, that's what it is.cut");
    player->setInvulnerable(InvulnerabilityReason::CutScene, false);
}

void chugInvulnerabilityPotion()
{
    Character * player = getPlayer();
    player->setInvulnerable(InvulnerabilityReason::Potion, true);
    sleepUntil(now() + 5.0);
    player->setInvulnerable(InvulnerabilityReason::Potion, false);
}

With this approach, we check all of the invulnerability flags instead of a single flag. The player is invulnerable if any of them is set. As long as there’s only one bit of code setting each individual flag we don’t have to worry about the separate bits of code tripping over each other.

This approach can work, but it takes discipline. If someone gets lazy and reuses an InvulnerabilityReason in a different bit of code, then everything can come crashing down. And adding a new value to the InvulnerabilityReason enum every time we have a new bit of code that wants to tweak invulnerability will quickly get annoying.

We might think about eliminating entanglement by tracking an invulnerability count. Instead of a single flag, we count how many bits of code want the character to be invulnerable. If any bit of code wants the character invulnerable, then they’re invulnerable. This leads to a pretty simple push-pop model :

void playCelebrationCutScene()
{
    Character * player = getPlayer();
    player->pushInvulnerability();
    playCutScene("I'm getting my own ship.cut");
    player->popInvulnerability();
}

void chugInvulnerabilityPotion()
{
    Character * player = getPlayer();
    player->pushInvulnerability();
    sleepUntil(now() + 5.0);
    player->popInvulnerability();
}

A push-pop model like this works. Once you’re used to the idiom, it’s easy to understand. It’s easily extended when a new bit of code wants to monkey with damage, and different bits of code can push and pop the invulnerability count independently without breaking things.

We’ve still left easy usage mistakes, though. If your code forgets to call pop​In⁠vulnerability , the character stays invulnerable forever. That’s an easy mistake to make—maybe you add an early exit to your function, not realizing that cleanup is required. Or maybe you try to fix this by popping in your early exit case and end up accidentally popping twice, with even more mysterious results. 6

Better to eliminate the usage mistake entirely. The easiest way to do this is to wrap the push-pop in a constructor-destructor pair. Then the compiler becomes our ally:

void playCelebrationCutScene()
{
    Character * player = getPlayer();
    InvulnerableToken invulnerable(player);

    playCutScene("see you later, losers.cut");
}

void chugInvulnerabilityPotion()
{
    Character * player = getPlayer();
    InvulnerableToken invulnerable(player);

    sleepUntil(now() + 5.0);
}

This is pretty tight. We’ve made it hard to get things wrong. It’s still possible to screw things up, of course. If you create an InvulnerableHandle someplace where it’s not going to be destroyed (embedded in a structure you’ve stored on the heap, say), things can still go sideways. In practice, though, we’ve found that object lifetimes are something our programmers typically get right, and leveraging it to provide robust management of shared state works really well for us.

Detecting Mistakes Is Good, but Making Them Impossible to Express Is Better

In these examples, we were able to eliminate most of the ways to screw up, usually by enlisting the compiler to lend a hand. Anything the compiler catches makes the programmer’s job easier. The techniques we used aren’t complicated. We’ve applied them to lots of disparate problems in Sucker Punch games. And if things are structured so that you can’t even express the error, even better! But Douglas Adams has something to say about the matter: 7

A common mistake that people make when trying to design something completely foolproof is to underestimate the ingenuity of complete fools.

He’s right, of course. There’s no perfect answer, no way to prevent all possible usage errors. We can stop the user from shooting themselves directly in the foot, but it’s hard to stop all the possible ricochets. Our goal isn’t a completely foolproof design—just a design that makes it really easy to get things right and really hard to get things wrong .

Despite our inability to make our designs completely foolproof, every bit of foolishness we can prevent makes our systems more robust. So look for opportunities to eliminate failure cases from your design from the start.

1 No kidding .

2 OK, in very limited cases this isn’t true. If you’re using format strings that exactly match printf format strings and are willing to dive deep into your compiler’s documentation, you can probably find a way to leverage the compiler’s printf support for your case. I wouldn’t recommend this. You’re throwing good money after bad.

3 In this case, Irish. Per an undisclosed translation app, “Tá $%.2f dlite do %s an ráithe seo.”

4 Literally—the C language and printf were invented very shortly after Unix time value zero. And printf is still used 50 years later, an unlikely fate for any code I’ve ever written.

5 I adapted these examples from equivalent code written in our scripting language, which has built-in support for asynchronous programming through co-routines. The sleepUntil call doesn’t block other code from running; neither does playCutScene in the last example. That can lead to complications, as we shall see.

6 I’ve made both of these mistakes more than once, for the record.

7 Douglas Adams, Mostly Harmless (Del Rey, 1993).