paulund

Cognitive Load

Cognitive Load

Cognitive load is how much mental effort a developer needs to expend in order to complete a task. When reading code, you need to hold many things in your head at once, including:

  • Variables
  • Methods
  • Classes
  • Logic flow

The average person can only hold 7 plus or minus 2 items in their working memory at once. Once your code reaches this many moving parts, it becomes hard to follow.

This is why it's important to keep your code simple and easy to understand.

What Can Lead To Cognitive Load In Code

Cognitive load refers to the amount of mental effort required to process information, make decisions, and complete tasks. The concept is rooted in cognitive psychology and is commonly used to understand how people learn and perform complex work. In programming, cognitive load affects how well you can:

  • Understand code (yours or someone else’s).
  • Debug and fix issues.
  • Design scalable solutions.
  • Balance multiple tasks like writing code, testing, and documentation.

For example, if you have a condition that looks like this:

if ($user->role === 1 && $user->status === 1 || $user->role === 2 && $user->status === 1) {
    // Do something
}

The problem with this condition is that you need to know what role 1 and role 2 represent, and what status 1 means.

You can improve this by extracting the checks into well-named methods:

if ($user->isAdmin() || $user->isModerator()) {
    // Do something
}

Each method performs the role and status checks internally and returns a boolean. Just by reading the condition you can understand what it does. If you need to dig deeper, you can look inside isAdmin and see that role === 1 maps to an admin user.

Types Of Cognitive Load

There are three main types of cognitive load:

  • Intrinsic Load: The inherent difficulty of the task. For example, learning PHP’s syntax and basic constructs is easier than mastering advanced concepts like dependency injection or creating custom frameworks.
  • Extraneous Load: Unnecessary distractions or complexities that make a task harder. Poorly written code, unclear documentation, or an over-complicated IDE setup contribute to this.
  • Germane Load: The mental effort directed toward understanding and solving problems. Writing algorithms or implementing design patterns typically falls into this category.

The Impact of Cognitive Load on Coding

  1. Mental Fatigue

High cognitive load leads to mental fatigue, which reduces your ability to focus and increases the likelihood of errors. For example, juggling multiple PHP frameworks in a single project can quickly overwhelm your mental capacity.

  1. Decreased Code Quality

When cognitive load is high, you become more prone to cutting corners or missing edge cases. This can result in:

  • Spaghetti code.
  • Poorly named variables.
  • Functions that do too much.
  1. Slower Debugging

Debugging requires attention to detail and logical reasoning. When your cognitive load is at capacity, tracing a bug through a complex codebase becomes exceptionally difficult.

  1. Hindered Learning

When learning new PHP tools, libraries, or best practices, high cognitive load slows your progress. For instance, trying to learn Laravel whilst simultaneously building a production application can be overwhelming.

Strategies to Reduce Cognitive Load

  1. Write Clean and Simple Code

Adopt coding standards such as PSR (PHP Standard Recommendations) to maintain consistency. Avoid over-engineering; simplicity is the key to reducing both intrinsic and extraneous load.

Here’s an example:

Before:

function processData($data) {
    if (isset($data["name"])) {
        $name = $data["name"];
    } else {
        $name = "Unknown";
    }

    if (isset($data["age"])) {
        $age = $data["age"];
    } else {
        $age = 0;
    }

    return ["name" => $name, "age" => $age];
}

After:

function processData($data) {
    $name = $data["name"] ?? "Unknown";
    $age = $data["age"] ?? 0;

    return ["name" => $name, "age" => $age];
}
  1. Use Tools and Automation
  • Linting Tools: Automatically catch syntax and styling issues.
  • IDEs: Modern IDEs like PHPStorm provide intelligent suggestions and refactoring tools.
  • Code Snippets: Reuse boilerplate code to save mental effort.
  1. Break Tasks into Smaller Steps

Decompose complex features into smaller, manageable tasks. For instance, building an API endpoint can be divided into defining routes, creating controllers, and testing.

  1. Refactor Regularly

Refactor code to reduce complexity. Break large functions into smaller ones and replace magic numbers with constants.

Example:

function calculateDiscount($price) {
    $discountRate = 0.1; // Magic number
    return $price - ($price * $discountRate);
}

Refactored:

const DISCOUNT_RATE = 0.1;

function calculateDiscount($price) {
    return $price - ($price * DISCOUNT_RATE);
}
  1. Prioritise Documentation

Write clear, concise comments and maintain up-to-date documentation. This reduces the cognitive load for anyone revisiting the code later, including yourself.

  1. Limit Multitasking

Focus on one task at a time to avoid spreading your mental resources too thin.

  1. Invest in Learning

Dedicate time to learning PHP fundamentals and advanced concepts. A strong foundation reduces intrinsic cognitive load over time.

Final Thoughts

Cognitive load management is an often-overlooked aspect of software development. By understanding its impact and adopting strategies to reduce it, developers can improve their efficiency, write cleaner code, and have a more satisfying experience overall.

Taking small, deliberate steps to minimise cognitive load can have a profound effect on your productivity. Pick one or two of the strategies above and see how they change your workflow.