phanalist

E0016: The “Brain Drain” Rule (Cognitive Complexity)

Cognitive Complexity is a score that tells you how much “brain power” it takes to read your code.

Think of your brain like a small backpack. Every time you add an if, a loop, or a switch, you put a heavy rock in that backpack. If you put too many rocks in, your backpack breaks, and you can’t understand the code anymore!

The Rules of the Backpack:

  1. Each decision costs 1 rock: Every if, while, for, and foreach adds 1 to your score.
  2. Nesting costs EXTRA: If you put an if inside another if, the second one is much heavier!
    • An if at the top level is 1 point.
    • An if inside that is 2 points.
    • An if inside that is 3 points.
  3. Logical “AND/OR” cost rocks: Using && and || makes your brain work harder to track all the conditions.

❌ The “Heavy Backpack” Example (High Complexity)

This code is hard to read because it keeps nesting deeper and deeper.

public function checkAccess($user, $job) {
    if ($user->isLoggedIn()) {          // +1
        if ($user->hasPermission()) {   // +2 (Nested!)
            if ($job->isActive()) {     // +3 (Deeply Nested!)
                return true;
            }
        }
    }
    return false;
}

✅ The “Light Backpack” Example (Low Complexity)

This code does the exact same thing, but it’s “flat.” Your brain only has to deal with one thing at a time.

public function checkAccess($user, $job) {
    if (!$user->isLoggedIn()) return false;    // +1
    if (!$user->hasPermission()) return false; // +1 (Not nested!)
    if (!$job->isActive()) return false;       // +1 (Not nested!)

    return true;
}

The Junior’s Rule of Thumb:

If Phanalist tells you your Cognitive Complexity is too high, it means you’re making the reader’s brain work too hard. Try to “flatten” your code by using early returns!