[Repost] Cognitive Load Is What Matters

There are so many buzzwords and “best practices” out there, so let’s focus on something more basic: how much confusion a developer feels when reading code.

Confusion costs time and money. It comes from high cognitive load. This isn’t some fancy abstract idea. It’s a basic human limit.

Because we spend far more time reading and understanding code than writing it, we should keep asking ourselves whether we are putting too much cognitive load into our code.

Original URL: https://github.com/zakirullin/cognitive-load/tree/main
Original Author: Artem Zakirullin

Cognitive load

Cognitive load is how much a developer needs to think in order to complete a task.

When reading code, you keep things like variable values, control flow logic, and call sequences in your head. On average, a person can hold about four chunks in working memory. Once you hit that limit, understanding anything gets dramatically harder.

Imagine you’re asked to fix a bug in a completely unfamiliar project. You’re told a really smart developer wrote it before you, using fancy architectures, trendy libraries, and cutting-edge techniques. Simply put, the previous developer handed you a huge cognitive load.

Cognitive Load

We should minimize cognitive load in our projects as much as possible.

Types of cognitive load

Intrinsic: comes from the difficulty of the task itself. It is part of software development and cannot be reduced.

Extraneous: comes from how information is presented. It is usually caused by things unrelated to the task, like clever developer tricks, and we can get rid of it. The rest of this post is about extraneous cognitive load.

Intrinsic vs Extraneous

Let’s jump straight into concrete examples of extraneous cognitive load.


We’ll track the level of confusion like this:

🧠: Fresh working memory, no cognitive load yet

🧠++: Two items loaded into working memory, cognitive load increasing (more + means heavier load)

🤯: More than 4 items loaded into working memory (overflow!)

Our brains are obviously much more complex and mysterious than this; this is just a rough model to show how cognitive load builds up.

Complex conditionals

1
2
3
4
5
if val > someConstant // 🧠+
&& (condition2 || condition3) // 🧠+++, the first condition must be true, and either c2 or c3 must be true
&& (condition4 && !condition5) { // 🤯, and right here our brain completely short-circuits
...
}

Nested ifs

1
2
3
4
5
if isValid { // 🧠+, at this step we only care about isValid
if isSecure { // 🧠++, now we have to hold both isValid and isSecure in mind
stuff // 🧠+++
}
}

Compare that with early returns:

1
2
3
4
5
6
7
8
9
if !isValid
return

if !isSecure
return

// 🧠, we don't have to remember what already returned; getting here means all checks passed

stuff // 🧠+

We can focus purely on the happy path and free working memory from tracking preconditions.

Inheritance nightmare

Suppose we’re asked to change something for admin users 🧠:

AdminController extends UserController extends GuestController extends BaseController

Oh, part of the behavior lives in BaseController, let’s check it: 🧠+

GuestController introduces basic role handling: 🧠++

UserController overrides some of that behavior: 🧠+++

Finally, we reach AdminController. Time to start coding! 🧠++++

Oh, wait: there’s also a SuperuserController that extends AdminController. If we change AdminController, we might break subclasses inheriting from it, so we need to check SuperuserController first: 🤯

Prefer composition over inheritance. I won’t repeat the full argument here; there are plenty of good resources on this.

Too many small methods, classes, or modules

The terms methods, classes, and modules are interchangeable below.

Rules like “methods should be under 15 lines” or “classes should always be small” have turned out to be wrong in practice.

Deep module: simple interface, complex functionality behind it.

Shallow module: interface is relatively complex compared to the tiny amount of functionality it provides.

Deep module

When a project has too many shallow modules, it becomes hard to follow. You don’t just have to remember what each module does; you also have to keep all the interactions between them in your head. To understand what one shallow module is for, you end up opening every related module first. 🤯

Information hiding matters a lot, and shallow modules barely hide any complexity.

I have two side projects, each around 5,000 lines of code. The first has 80 shallow classes; the second has just 7 deep classes. I hadn’t touched either of them for a year and a half.

When I came back to maintain them, reconstructing how those 80 classes in the first project interacted was brutal. I had to rebuild a huge mental model before writing a single line. The second project clicked right away because it only had a few deep classes with simple interfaces.

The best components are those that provide powerful functionality yet have simple interfaces.

John K. Ousterhout

UNIX I/O has a very simple interface, with just five basic calls:

1
2
3
4
5
open(path, flags, permissions)
read(fd, buffer, count)
write(fd, buffer, count)
lseek(fd, offset, referencePosition)
close(fd)

Modern implementations behind that interface span hundreds of thousands of lines of code. Despite all that underlying complexity, the interface is simple, so it’s easy to use.

This deep-module example comes from John K. Ousterhout’s book A Philosophy of Software Design, which explains the nature of complexity in software and pairs well with David Parnas’s classic paper On the Criteria to Be Used in Decomposing Systems into Modules. Both are must-reads. Further reading: It’s probably time to stop recommending Clean Code, Small Functions considered Harmful.

P.S. If you think I’m arguing for bloated “God objects” that do everything, you’ve missed the point.

Shallow modules and SRP

Too often, we follow the vague slogan “a module should do only one thing” and end up creating piles of shallow modules. What even counts as “one thing”? Instantiating an object is “one thing,” right? By that logic, names like MetricsProviderFactoryFactory seem perfectly reasonable. Yet when a class’s name and interface are harder to parse than its entire implementation, what kind of abstraction is that? Something has clearly gone wrong.

Jumping back and forth between shallow components is exhausting; linear thinking is far more natural for human brains.

We change software to serve users and stakeholders, and we are responsible to them.

A module should be responsible to one, and only one, user or stakeholder.

That’s the actual meaning of the Single Responsibility Principle (SRP). Simply put, if you introduce a bug in one place and people from two different business domains come complaining, you’ve violated SRP. It has nothing to do with how many lines or steps live inside a module.

Even then, that phrasing still causes more harm than good, because even the same person can read it differently from one day to the next. A better way to think about SRP is through cognitive load: having to remember that “changing this module causes ripple effects across unrelated business flows” taxes your working memory. That’s all there is to it.

Too many shallow microservices

The shallow-vs.-deep module principle is scale-invariant: it applies just as much to microservice architectures. Too many shallow microservices hurt more than they help. The industry is already moving back toward “macroservices” (deeper services instead of shallow ones). One of the worst, hardest-to-fix failure modes is the “distributed monolith,” usually caused by slicing services far too thinly.

I once consulted for a startup where a team of just five developers had built a product with 17(!) microservices. They were nearly 10 months behind schedule and still nowhere close to launch. Every new feature required changes across four or more services. Debugging integration issues became much harder. Both time-to-market and developer cognitive load were off the charts. 🤯

Is that really the right way to handle uncertainty in a brand-new system? Getting logical boundaries right on day one is notoriously difficult. The smart move is to defer decisions as long as possible so you have more information when you make them. Once you lock in network boundaries upfront, changing them later is painful. Yet the team’s only justification for this architecture was: “FAANG proved microservices work.” Wake up and stop living in a fantasy.

In the famous Tanenbaum–Torvalds debate, Tanenbaum argued that Linux’s monolithic design was flawed and obsolete and should be replaced with a microkernel. In theory and aesthetically, microkernels look cleaner. In practice, thirty years later, the microkernel-based GNU Hurd is still in development, while monolithic Linux runs everywhere. The page you’re reading is powered by Linux; your smart kettle is powered by Linux (monolithic Linux).

A well-designed monolith with cleanly isolated modules is often more flexible than a fleet of microservices, and it carries a fraction of the cognitive cost. Only when independent deployment genuinely matters (for example, when scaling engineering teams) should you start adding network boundaries between modules that might later become microservices.

Feature-rich languages

Whenever our favorite programming language rolls out shiny new features, we get excited, spend time learning them, and rush to use them in our code.

When a language has too many ways to do the same thing, you can easily burn half an hour tinkering with a few lines just to pick a feature. Even worse, when you come back to read that code months later, you have to replay that whole thought process all over again!

Not only do you have to understand a complex program, you also have to figure out why on earth you chose that specific feature to solve it. 🤯

Rob Pike put it well:

Reduce cognitive load by limiting the number of choices.

Having language features is fine, as long as they are orthogonal (independent of one another, so they don’t interfere or collide in surprising ways).

Thoughts from an engineer with 20 years of C++ experience ⭐️
A few days ago, while browsing my RSS reader, I noticed roughly three hundred unread articles under my "C++" tag. I haven't read a single C++ article since last summer, and it feels amazing!

I've used C++ for 20 years now, nearly two-thirds of my life. Most of that experience went into dealing with its darkest corners (all kinds of undefined behavior). It's non-transferable knowledge, and letting it all go feels strangely liberating.

For instance, can you believe that || means two different things in requires ((!P || !Q)) versus requires (!(P || Q))? The first is a constraint disjunction, while the second is an ordinary logical OR, and their behavior is not the same.

Before C++20, for a trivial type, you couldn't just allocate storage and memcpy bytes into it, because that didn't actually start the object's lifetime. C++20 fixed this, yet the cognitive load of the language still went up instead of down.

Cognitive load keeps growing even when problems get fixed. As a professional, I now have to know what was fixed, when it was fixed, and how things broke before the fix. Sure, C++ is great at supporting legacy code, which also means we inherit all the legacy quirks that come with it. Just last month a colleague asked me about some C++03 behavior. 🤯

There used to be 20 ways to initialize an object. Then uniform initialization was added. Now we have 21 ways to initialize an object. By the way, does anyone remember the exact overload-resolution rules for selecting a constructor from an initializer list? Something about implicit conversions with the least information loss, except if the value is statically known, then... 🤯

None of this added cognitive load comes from the business task at hand or intrinsic domain complexity. It exists purely for historical reasons (extraneous cognitive load).

I had to set personal rules: if a line of code isn't immediately obvious and requires remembering a specific clause of the standard, it's better not to write it that way. By the way, the standard is roughly 1,500 pages long.

I'm not bashing C++. I love the language. I'm just tired.

Business logic and HTTP status codes

Suppose the backend returns the following status codes:

401 means the JWT token has expired

403 means insufficient permissions

418 is a playful status meaning the server refuses to brew coffee because it’s a teapot (“I’m a teapot”)

When a frontend developer integrates the login API, they have to load this mapping into their head:

401 means JWT expired // 🧠+, okay, just keep that in mind for now

403 means insufficient permissions // 🧠++

418 “I’m a teapot” // 🧠+++

Hopefully, the frontend developer creates some “numeric status -> meaning” dictionary on their side so future teammates don’t have to reconstruct it mentally.

Then QA joins the project: “Hey, I got a 403. Does that mean the token expired or permissions are missing?”

QA can’t even test smoothly until they rebuild the mental model the backend developer invented.

Why force anyone to keep a custom status-code mapping in working memory? It’s much cleaner to decouple business details from the HTTP transport layer and return a self-describing error code right in the response body:

1
2
3
{
"code": "jwt_has_expired"
}

Now, frontend developer’s cognitive load: 🧠 (clean slate, zero extra load)

QA engineer’s cognitive load: 🧠

The same rule applies to magic numbers everywhere (in databases or anywhere else). Self-describing strings are almost always a better choice. We’re long past the era of squeezing bytes into 640K of RAM.

Teams regularly waste hours debating the exact distinction between 401 and 403 and making judgment calls based on personal interpretation. Every new hire has to relearn that reasoning. Maybe you even wrote Architecture Decision Records (ADRs) to explain your choice, and still nobody reads them until something breaks. Drawing the line between “client error” and “server error” is straightforward enough; beyond that, the boundaries get blurry fast.

P.S. Distinguishing between “authentication” and “authorization” is itself an unnecessary mental tax. Using simpler terms like “login” and “permissions” immediately lowers cognitive load.

Abusing the DRY principle

Don’t Repeat Yourself is one of the first rules drilled into every software engineer. It gets ingrained so deeply that we develop zero tolerance for duplication, even for a few lines of code. As a general guideline, it’s solid. Taken to extremes, though, it piles on heavy cognitive load.

Modern software is usually built from logically separate components, often spread across different repositories and services. In your push to remove every trace of duplication, you can end up tightly coupling components that had no business knowing about each other. Now a change in one place causes surprising breakage somewhere seemingly unrelated, and you lose the freedom to modify or replace a single component without rippling through the whole system. 🤯

The exact same trap shows up inside a single monolith. You spot a surface-level similarity (one that may not hold up over time) and extract a shared abstraction too early. That forced abstraction makes the codebase harder to change and harder to extend.

As Rob Pike put it:

A little copying is better than a little dependency.

Because we’re allergic to “reinventing the wheel,” we happily pull in huge, complex third-party libraries just to use a couple of tiny helpers we could have written ourselves in ten minutes.

Every dependency you pull in becomes part of your codebase. When something breaks in production, stepping through a 10+ layer stack trace inside someone else’s library is pure misery.

Tight coupling with a framework

Frameworks are packed with “magic.” When we bind our code tightly to a framework, we force every future developer on the team to learn that magic first, and that ramp-up can take months. Frameworks are great for getting an MVP out the door in a few days, yet over the long haul they often introduce heavy complexity and cognitive load.

Worse still, sooner or later a business requirement shows up that doesn’t fit the framework’s mold, and the framework starts fighting you at every turn. Before long, teams fork the framework and maintain a custom internal version. Imagine the cognitive load dumped on a new hire who now has to learn your forked framework just to ship a feature. 🤯

That doesn’t mean you should build everything from scratch!

You can structure your code to stay independent of any specific framework. Instead of stuffing your business logic inside the framework, keep your core logic framework-agnostic and call into framework components from the edges, treating the framework like a library instead of a cage. That way, new developers can jump into the business logic on day one without having to master framework internals first.

Why I Hate Frameworks

Hexagonal / Onion architecture

In software engineering, architectural diagrams like these have a certain appeal.

For years, I was a vocal advocate of Onion Architecture. I used it across multiple projects and pushed other teams to adopt it too. The result? Complexity ballooned, and the file count doubled overnight. Half the time, we felt like we were writing endless glue code. Every requirement change forced edits across multiple layers of abstraction, turning development into a tedious grind. 🤯

Jumping from call to call to trace a bug quickly is needed for fast debugging. With layers upon layers of indirection, pinpointing a failure means chasing a branching trail of seemingly unrelated interfaces, and every hop eats up working memory. 🤯

It sounds intuitive on paper, yet every time we actually applied it, the costs outweighed the benefits. In the end, we dropped Onion Architecture altogether in favor of plain, time-tested Dependency Inversion. No ports and adapters to memorize, no extra horizontal abstraction layers, and none of the extraneous cognitive load that comes with them.

Don’t add abstraction layers for the sake of “architecture.” Add them only when you have a real, concrete need for extensibility. Layers of abstraction aren’t free of charge; they cost working memory.

If you think all those layers will let you easily swap out your database or core dependencies someday, think again. Changing storage engines is painful for plenty of reasons, and trust me, the data-access abstraction is the least of your worries. At best, it might save 10% of the migration effort (if that); the real killers are incompatible data models, wire protocols, distributed-systems edge cases, and implicit interfaces (Hyrum’s Law). Why pay a daily tax in cognitive load for an insurance policy that won’t even pay out? Most of the time, you’ll never swap out that core dependency anyway.

Yes, these layered styles helped nudge applications away from “database-centric” designs toward “infrastructure-independent” core logic, but that idea isn’t unique to them.

These architectures aren’t basic principles; they’re opinionated derivations built on top of simpler foundations. Why commit to someone else’s opinions when you can stick directly to the basics: Dependency Inversion, managing cognitive load, and information hiding? (Discussion)

Domain-Driven Design (DDD)

Even though Domain-Driven Design (DDD) is widely misunderstood, parts of it are genuinely valuable.

Saying “we write our code in DDD” is actually a bit odd, because DDD is primarily about the problem space, not the solution space.

Note:

  • Problem space: the business domain itself, meaning the real-world problems and requirements you’re trying to solve.

  • Solution space: the engineering design and technical implementation built to solve those problems.

Ubiquitous language, domains, bounded contexts, aggregates, and event storming all live in the problem space. They help us understand the business and draw clean boundaries, giving developers, domain experts, and business stakeholders a shared language. Yet teams routinely focus on solution-space details (folder layouts, services, repositories) while missing DDD’s actual value in the problem space.

Your personal interpretation of DDD is almost certainly idiosyncratic and subjective. If you organize your codebase around that personal interpretation (piling on extraneous cognitive load), every future developer who touches it is set up to fail. 🤯

Examples

  • “Our architecture is a boring CRUD app: a Python monolith backed by Postgres.”
  • How Instagram scaled to 14 million users with just 3 engineers.
  • The companies that made us say “wow, these people are really smart“ largely failed.
  • One function ties the whole system together. If you want to see how the system works, read it.

These architectures are boring, easy to understand, and approachable without melting anyone’s brain.

Invite junior developers to your architecture reviews. They will quickly point out the parts of your codebase that demand too much mental gymnastics.

Cognitive load in familiar projects

The problem is that familiarity is not simplicity. They feel the same (both let you move through code easily), but for very different reasons. Every “clever” (read: self-indulgent) or non-idiomatic trick you use puts real pain on the next person trying to learn it. Once they’ve suffered through learning it, it feels easy to them too. That’s why it’s so hard to see how to simplify code you already know well, and why I always ask the “new kid” to review code before it sets in their head!

Chances are the previous authors built up that giant mess one small step at a time, and you’re the first person trying to swallow it all at once.

In my classes, I tell the story of a massive SQL stored procedure we once encountered with a giant WHERE clause spanning hundreds of lines of conditions. Someone asked how anyone could let it get that bad. I told them: “When there were two or three conditions, adding one more didn’t seem to hurt. When there were twenty or thirty, adding one more still didn’t seem to matter!”

Nothing in a codebase exerts a “simplifying force” except deliberate human effort. Simplification takes work, and people rarely make time for it.

Once you’ve internalized a project’s mental model into long-term memory, you stop feeling its cognitive load.

img

The more mental models a newcomer has to learn, the longer it takes them to become productive.

Whenever someone new joins your project, pay attention to their confusion (pair programming helps a lot here). If they stay stuck in confusion for more than 40 minutes, your code needs work.

When you keep cognitive load low, new engineers can start contributing meaningful code within their first few hours.

Conclusion

Imagine that what we concluded in chapter two turned out not to be true. If that were the case, then the conclusion we just dismissed, along with the one we treated as valid in the previous chapter, might also turn out to be wrong. 🤯

Feel that? Not only did you have to jump back through the article to make sense of it (shallow modules!), the paragraph itself was a knot to untangle. We just injected pointless cognitive load straight into your head. Please don’t do that to your teammates.

img

Eliminate every bit of cognitive load that doesn’t belong to the work itself.


Cognitive load and interruptions
Coding principles and experience