Complexity is the enemy of scale.

You know that simpler code is better—as simple as possible, but no simpler, per Rule 1 —but that Rule becomes harder to follow as the scale of your project increases. It’s easy to keep your code simple for simple problems, but as code grows and matures it naturally grows more complicated. And as it grows more complicated, it becomes harder to work with—you lose the ability to keep all the details in your head. Every time you attempt to fix a bug or add a new feature, you trip over unpredictable side effects—every step forward is matched by an unexpected step backward.

Part of the solution is to look for opportunities to keep things simple or make things simple. That’s Rule 1 . But complexity can’t be eliminated entirely; any moderately functional and long-lived bit of software is going to have to weather the complexity inherent in the problems the software solves. But complexity can be managed.

To borrow a sports cliché: you can’t stop complexity, you can only hope to contain it.

Along those lines, a useful strategy is to isolate any complexity you can’t eliminate. If the internal details of some bit of code are complicated, but its external interface is simple, the complexity presents less of a problem. When you’re inside that bit of code you have to cope with its internal complexity, but outside the code you don’t have to worry about it.

A Simple Example

Consider the sine and cosine functions in your language of choice. The external interface is simple—call the function, get the sine or cosine of the angle passed in. The internal details are complicated, though.

I was many years old before I wondered how these functions were actually implemented. Until then, as far as I was concerned, they just magically produced the right answer 1 …and this blissful ignorance was perfectly OK! Whatever complexity existed inside of the implementation of the sine and cosine functions didn’t affect how I used them. They just worked in the way I expected.

You can draw a circle without knowing the implementation details of sine and cosine:

void drawCircle(Point center, float radius, Color color)
{
    int count = int(ceil(pi / acos((radius - 1.0) / radius)));
    Point previousPoint = center + Vector(radius, 0.0, 0.0);
    for (int index = 1; index <= count; ++index)
    {
        float angle = 2.0 * pi * index / count;
        Point nextPoint = center + 
                          radius * Vector(cosf(angle), sinf(angle), 0.0);

        drawLine(previousPoint, nextPoint, color);

        previousPoint = nextPoint;
    }
}

There’s complexity somewhere inside sinf and cosf (the C standard library’s sine and cosine functions for 32-bit floats), but it doesn’t leak out through the simple abstraction of those functions into the rest of your code. 2 The complexity is safely localized.

Hiding Internal Details

The same rule applies to your own code. Whenever possible, you should isolate complexity, confining it to clearly defined sections of your code.

Imagine that you’ve got a list of customer records, and you’re writing a function to return a list of customers who’ve recently purchased something. The customer records look like this :

struct Customer
{
    int m_customerID;
    string m_firstName;
    string m_lastName;
    Date m_lastPurchase;
    Date m_validFrom;
    Date m_validUntil;
    bool m_isClosed;
};

The complexity here is that not all customer records in your list are valid. Some customer accounts have expired or haven’t been activated yet, and other accounts have been closed by the customers. Your function will need to exclude those invalid customer records:

void findRecentPurchasers(
    const vector<Customer *> & customers,
    Date startingDate,
    vector<Customer *> * recentCustomers)
{
    Date currentDate = getCurrentDate();

    for (Customer * customer : customers)
    {
        if (customer->m_validFrom >= currentDate &&
            customer->m_validUntil <= currentDate &&
            !customer->m_isClosed &&
            customer->m_lastPurchase >= startingDate)
        {
            recentCustomers->push_back(customer);
        }
    }
}

The complexity introduced by invalid customer records isn’t localized—it has leaked into this unrelated function. Every loop through the customer list now has to check for invalid customer records. And if the rules determining validity change, every one of those loops will have to be updated.

The code in the previous example is pretty bad design, honestly. There’s no reason to duplicate the customer validity check in every loop—one of the promises of object-oriented design was making it easier to hide exactly this sort of complexity. At a minimum, the eligibility rule should be encapsulated:

struct Customer
{
    bool isValid() const
    {
        Date currentDate = getCurrentDate();

        return m_validFrom >= currentDate &&
               m_validUntil <= currentDate &&
               !m_isClosed;
    }

    int m_customerID;
    string m_firstName;
    string m_lastName;
    Date m_lastPurchase;
    Date m_validFrom;
    Date m_validUntil;
    bool m_isClosed;
};

That makes the loop a little bit simpler:

void findRecentPurchasers(
    const vector<Customer *> & customers,
    Date startingDate,
    vector<Customer *> * recentCustomers)
{
    Date currentDate = getCurrentDate();

    for (Customer * customer : customers)
    {
        if (customer->isValid() &&
            customer->m_lastPurchase >= startingDate)
        {
            recentCustomers->push_back(customer);
        }
    }
}

That’s only a half-measure, though. A better solution lies upstream: instead of looping over all customers, it should loop over valid customers. Whatever bit of your code provides a list of customers should also provide a list of valid customers, likely computed from the list of all customers. Then your code will be appropriately simple:

void findRecentPurchasers(
    const vector<Customer *> & validCustomers,
    Date startingDate,
    vector<Customer *> * recentCustomers)
{
    Date currentDate = getCurrentDate();

    for (Customer * customer : validCustomers)
    {
        if (customer->m_lastPurchase >= startingDate)
        {
            recentCustomers->push_back(customer);
        }
    }
}

With this change, all the complexity is localized to the function that returns a list of valid customers. Code like findRecentPurchasers doesn’t need to worry about customer validity, and is easier to write and understand as a result .

Distributed State and Complexity

Object-oriented design can help localize complexity, but it’s not a panacea. It’s easy to get in trouble, especially when you’ve distributed state across a set of objects instead of localizing it in a single object.

Distributing state isn’t necessarily a problem! Sometimes the most natural way of modeling a system is to create multiple objects that jointly manage the system’s state. The promise of object-oriented design is that this sort of multiple-object design can still hang together—each object manages its own state, with well-defined interactions between the objects.

That promise of an easy-to-understand object-oriented design won’t be fulfilled without some careful coding, though. It’s easy to end up with pretty rickety code if you’re trying to do something that depends on the current state of multiple objects.

Here’s an invented example. You’re building a stealth game, in which part of the fun is skulking around without getting spotted by your enemies. In this family-friendly example, the player is trying to sneak up behind other characters in order to tape “kick me” signs to their backs. To make this easier, you want to show a little “eye” icon on screen. The eye is closed when none of the player’s enemies can see them, but opens when an enemy has a clear line of sight to the player. A closed eye means the player is safe, while an open eye means they’re at risk of being spotted.

You’ve got a handful of objects and classes to model this: an object for the player, objects for all the other characters, an object for the eye icon, and an object that tracks which characters have a clear line of sight to which other characters. The last object, the awareness manager, provides a way for you to register a callback function that is called whenever a particular character is spotted by another character, and a second callback function that is called when that other character loses sight of the registered character.

Given these objects, an obvious way to implement this feature centers on the player object. The player object can implement an awareness callback function, then use that callback to keep count of how many other characters have spotted the player. If that count is zero, the player object sets the eye icon to closed; otherwise, it sets it to open.

The awareness manager looks like this :

class AwarenessEvents
{
public:

    virtual void OnSpotted(Character * otherCharacter);
    virtual void OnLostSight(Character * otherCharacter);
};

class AwarenessManager
{
public:

    int getSpottedCount(Character * character);
    void subscribe(Character * character, AwarenessEvents * events);
    void unsubscribe(Character * character, AwarenessEvents * events);
};

The eye icon is even simpler:

class EyeIcon
{
public:

    bool isOpen() const;
    void open();
    void close();
};

Given these objects, the player code is easy to write. Get an initial count from the awareness manager when the player object is created and implement the AwarenessEvents interface to catch changes. With an accurate count of other characters who can see the player, the eye icon can be opened or closed appropriately:

class Player : public Character, public AwarenessEvents
{
public:
    
    Player();

    void onSpotted(Character * otherCharacter) override;
    void onLostSight(Character * otherCharacter) override;

protected:

    int m_spottedCount;
};

Player::Player() :
    m_spottedCount(getAwarenessManager()->getSpottedCount(this))
{
    if (m_spottedCount == 0)
        getEyeIcon()->close();

    getAwarenessManager()->subscribe(this, this);
}

void Player::onSpotted(Character * otherCharacter)
{
    if (m_spottedCount == 0)
        getEyeIcon()->open();

    ++m_spottedCount;
}

void Player::onLostSight(Character * otherCharacter)
{
    --m_spottedCount;

    if (m_spottedCount == 0)
        getEyeIcon()->close();
}

This isn’t bad code. There’s not a lot of it, and the code itself is pretty easy to read. There’s a bit of subtlety in choosing when to compare m_spottedCount to 0 , but it’s not hard to figure out. I think this code is defensible .

Capacitated?

Like all designs, though, this example evolves. To add a bit of a challenge for the player, we give it a twist: the eye icon should be open whenever the player is incapacitated. Or, to put it another way, the eye icon should be closed when none of the enemies have spotted the player and the player isn’t incapacitated.

In this case, the Player class has a setStatus method that’s called to mark changes in the player’s overall well-being. It’s easy enough to insert some code into setStatus to catch cases where the player becomes incapacitated or recovers to be fully…um, capacitated? Unincapacitated? Whatever. You only care about a change in the player’s status when m_spottedCount is zero, since otherwise the eye icon is already open. Similarly, when the spotted count’s zero-ness changes, you only have to worry about the eye icon if the player isn’t incapacitated :

enum class STATUS
{
    Normal,
    Blindfolded
};

class Player : public Character, public AwarenessEvents
{
public:
    
    Player();

    void setStatus(STATUS status);

    void onSpotted(Character * otherCharacter) override;
    void onLostSight(Character * otherCharacter) override;

protected:

    STATUS m_status;
    int m_spottedCount;
};

Player::Player() :
    m_status(STATUS::Normal),
    m_spottedCount(getAwarenessManager()->getSpottedCount(this))
{
    if (m_spottedCount == 0)
        getEyeIcon()->close();

    getAwarenessManager()->subscribe(this, this);
}

void Player::setStatus(STATUS status)
{
    if (status == m_status)
        return;

    if (m_spottedCount == 0)
    {
        if (status == STATUS::Normal)
            getEyeIcon()->close();
        else if (m_status == STATUS::Normal)
            getEyeIcon()->open();
    }

    m_status = status;
}

void Player::onSpotted(Character * otherCharacter)
{
    if (m_spottedCount == 0 && m_status == STATUS::Normal)
        getEyeIcon()->open();

    ++m_spottedCount;
}

void Player::onLostSight(Character * otherCharacter)
{
    --m_spottedCount;

    if (m_spottedCount == 0 && m_status == STATUS::Normal)
        getEyeIcon()->close();
}

This has added some complexity, especially in how the two overlapping conditions for showing the health indicator interact with each other. It still doesn’t seem disastrous, though.

The assumptions the code makes to minimize work—like only updating the eye icon in CPlayer::setStatus when the spotted count is zero—are more subtle now. It’s not too hard to figure out what’s going on, but there’s a price in complexity being paid for a little bit of efficiency .

Things Start to Get Foggy

The design evolves again, surprising absolutely no one. This time you’re adding weather effects. If the weather is foggy, then the eye icon should be open, just like when the player has been spotted or is incapacitated.

The weather system, like the awareness system, provides a simple query and callback API:

enum class WEATHER
{
    Clear,
    Foggy
};

class WeatherEvents
{
public:

    virtual void onWeatherChanged(WEATHER oldWeather, WEATHER newWeather);
};

class WeatherManager
{
public:

    WEATHER getCurrentWeather() const;
    void subscribe(WeatherEvents * events);
};

This fits into the pattern you used for awareness. Implement a weather callback, add some initialization code, mix some new logic into the existing checks, and you’ve got a working system:

class Player : 
    public Character, 
    public AwarenessEvents, 
    public WeatherEvents
{
public:
    
    Player();

    void setStatus(STATUS status);

    void onSpotted(Character * otherCharacter) override;
    void onLostSight(Character * otherCharacter) override;

    void onWeatherChanged(WEATHER oldWeather, WEATHER newWeather) override;

protected:

    STATUS m_status;
    int m_spottedCount;
};

Player::Player() :
    m_status(STATUS::Normal),
    m_spottedCount(getAwarenessManager()->getSpottedCount(this))
{
    if (m_spottedCount == 0 && 
        getWeatherManager()->getCurrentWeather() != WEATHER::Foggy)
    {
        getEyeIcon()->close();
    }

    getAwarenessManager()->subscribe(this, this);
    getWeatherManager()->subscribe(this);
}

void Player::setStatus(STATUS status)
{
    if (status == m_status)
        return;

    if (m_spottedCount == 0 &&
        getWeatherManager()->getCurrentWeather() != WEATHER::Foggy)
    {
        if (status == STATUS::Normal)
            getEyeIcon()->close();
        else if (m_status == STATUS::Normal)
            getEyeIcon()->open();
    }

    m_status = status;
}

void Player::onSpotted(Character * otherCharacter)
{
    if (m_spottedCount == 0 && 
        m_status == STATUS::Normal &&
        getWeatherManager()->getCurrentWeather() != WEATHER::Foggy)
    {
        getEyeIcon()->open();
    }

    ++m_spottedCount;
}

void Player::onLostSight(Character * otherCharacter)
{
    --m_spottedCount;

    if (m_spottedCount == 0 && 
        m_status == STATUS::Normal &&
        getWeatherManager()->getCurrentWeather() != WEATHER::Foggy)
    {
        getEyeIcon()->close();
    }
}

void Player::onWeatherChanged(WEATHER oldWeather, WEATHER newWeather)
{
    if (m_spottedCount == 0 &&
        m_status == STATUS::Normal)
    {
        if (oldWeather == WEATHER::Foggy)
            getEyeIcon()->close();
        else if (newWeather == WEATHER::Foggy)
            getEyeIcon()->open();
    }
}

Again, if you’ve just written code like this, it can feel reasonable. I’ve certainly written code like this and not felt bad about it!

It’s an evolution of the approach of the first version—look at the state of the world when the player object is initialized, then track changes in the world’s state to keep the eye icon up-to-date.

Conceptually, at least, there’s a common, repeated theme that grew out of the initial implementation—don’t bother updating the eye icon when its state shouldn’t change. When the weather changes, there’s no need to update the eye icon unless the spotted count is zero and the player isn’t incapacitated. If the spotted count is nonzero or the player is incapacitated, then the eye icon is already open and should remain so.

There are three variations of that idea in the code: for line of sight, player status, and current weather. The idea is expressed slightly differently for each of them, but it’s still just one idea, so it doesn’t seem that complicated.

Take a step back, though. It’s easy to see the shared idea when you’re writing the code—it’s your idea, after all! Imagine a teammate was looking at the last example. Will the basic idea be obvious to them? Uh…not so much.

If you know the idea—that is, don’t bother updating the eye icon when its state shouldn’t change—then you can see how the idea gets expressed in each of its repetitions. If you’re trying to go the other direction, to infer the basic idea from all the ways it’s expressed…well, then it’s not so obvious .

Rethinking the Approach

There’s a bigger problem here, though. The user-visible design of this feature is pretty simple—the eye icon should be closed when three conditions are met:

  • No enemy has spotted the player.

  • The player isn’t incapacitated.

  • The weather isn’t foggy.

As written earlier, you have five (!) separate implementations of this logic, all expressing those three conditions in different ways. That’s confusing. And there’s no simple, straightforward implementation of the rules—no place where you just check the three conditions. All five implementations are variations, all using bits of context to minimize the work done.

If your design changes in any way, you need to update each of the five implementations to match. For example, if you add a new WEATHER:HeavyFog state for the weather system, then you have to add checks for it in all the places you checked for WEATHER:Foggy .

More dangerously, what if the methods you’ve added change in some other way? Maybe you decide the player model should turn his head to look at any enemy that spots him, which means more code in CPlayer::onSpotted . Now you have to make sure that you’re not inadvertently breaking the stealth indicator.

There’s a pretty big problem underlying this code—it fails to localize the complexity of the design. You’ve got a simple design—the three conditions outlined at the start of the section—but you’ve scattered the implementation of that design across five separate implementations, all written slightly differently. Each condition adds a bit of complexity, and each bit of complexity interacts with all the other bits of complexity. They get tangled up very quickly.

If you’ve got a complicated idea, like the rules for when the eye icon is open or closed, then aim to express that complicated idea in one place.

In this case, that means one straightforward implementation of the three conditions. Then you can build the rest of the code around that implementation. Leaving the rest of the system alone, you might end up with something like this :

enum class STATUS
{
    Normal,
    Blindfolded
};

class Player : 
    public Character, 
    public AwarenessEvents, 
    public WeatherEvents
{
public:
    
    Player();

    void setStatus(STATUS status);

    void onSpotted(Character * otherCharacter) override;
    void onLostSight(Character * otherCharacter) override;

    void onWeatherChanged(WEATHER oldWeather, WEATHER newWeather) override;

protected:

    void refreshStealthIndicator();

    STATUS m_status;
};

Player::Player() :
    m_status(STATUS::Normal)
{
    refreshStealthIndicator();

    getAwarenessManager()->subscribe(this, this);
    getWeatherManager()->subscribe(this);
}

void Player::setStatus(STATUS status)
{
    m_status = status;

    refreshStealthIndicator();
}

void Player::onSpotted(Character * otherCharacter)
{
    refreshStealthIndicator();
}

void Player::onLostSight(Character * otherCharacter)
{
    refreshStealthIndicator();
}

void Player::onWeatherChanged(WEATHER oldWeather, WEATHER newWeather)
{
    refreshStealthIndicator();
}

void Player::refreshStealthIndicator()
{
    if (m_status == STATUS::Normal &&
        getAwarenessManager()->getSpottedCount(this) == 0 &&
        getWeatherManager()->getCurrentWeather() != WEATHER::Foggy)
    {
        getEyeIcon()->close();
    }
    else
    {
        getEyeIcon()->open();
    }
}

Here, all five implementations of the condition checks are collapsed into a single method, refreshStealthIndicator . That method is called whenever there’s a change in the conditions that method checks. There’s still a little bit of nonlocalized complexity, because the connection between the conditions you check and the callbacks that detect changes to those conditions isn’t obvious, but there’s way less of this than before.

And this implementation is linear with the number of conditions. If a new condition is added, you can add a new check to refreshStealthIndicator , write a bit of initialization code, and check for changes in the condition in one or two places. If you had 10 conditions, you’d have 10 times as much code.

That’s much better than the earlier examples that didn’t localize the complexity. In computer science terms, the code had quadratic complexity : every time you added a new condition, you added a new place to check all the conditions and a new check in each of the existing implementations of the logic. As a direct result, the number of lines of code implementing your design increased by the square of the number of conditions in that design. That’s not good! You’ll quickly run into a wall if your code’s complexity grows quadratically .

Localized Complexity, Simple Interactions

The thing you want to avoid at all costs is complicated interactions between different parts of your system. You can accept some complicated details, as long as the complexity is localized . A component with a simple interface and simple interactions but some complicated internal details won’t sink your project. A component with a complicated interface and complicated interactions might be your death knell, even if the internal details are simple.

A system built of components with simple interactions tends to have linear complexity. Each component makes the system a little bit more complicated, but the complexity stays manageable.

If the interactions between components are complicated, things get out of control fast .

If adding a new feature entails writing code in a lot of places, that’s a bad sign. At best, it means the new feature is a misfit with your existing code—and if every feature you add requires code in lots of places, then you’ve probably failed to localize complexity. That’s going to end in tears.

1 As I recall, my naive guess the first time my curiosity was piqued amounted to “big tables and linear interpolation.” I’m a little embarrassed by this guess; I knew what a Taylor series was at the time.

2 Both sinf and cosf are implementation-dependent and can be surprisingly complicated. I’ve tried to write short explanations here and failed; the important thing to keep in mind is that the functions don’t need to calculate an exact value, only a value that’s accurate to the resolution of a floating-point value, and that modulus math can reduce the angle to a convenient range for the approximation. Interestingly, there are x86 instructions to calculate sine and cosine, but modern compilers don’t use them unless explicitly ordered to do so. Those instructions, introduced in 1987, have known flaws that can’t be fixed for the sake of backward compatibility. Sigh.