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!
if, while, for, and foreach adds 1 to your score.if inside another if, the second one is much heavier!
if at the top level is 1 point.if inside that is 2 points.if inside that is 3 points.&& and || makes your brain work harder to track all the conditions.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;
}
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;
}
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!