Cognitive complexity evaluates code from a developer's perspective, accounting for:
break, continue, and goto statements interrupt mental flow&& and || require more mental trackingThe key insight is that a function with 10 decision points arranged linearly is easier to understand than one with 5 deeply nested decisions.
Stellarion calculates cognitive complexity using weighted scoring:
if, else if, elseswitch, for, while, do-whilecatch, try with resources&&, || operators (sequences count as one)Stellarion uses these thresholds to classify cognitive complexity:
| Score | Severity | Assessment |
|---|---|---|
| 1-10 | Low | Easy to understand |
| 11-15 | Moderate | Acceptable cognitive load |
| 16-25 | High | Difficult to comprehend |
| >25 | Critical | Extremely difficult, immediate attention required |
High cognitive complexity leads to:
Replace nested conditionals with early returns:
// Before (Cognitive: 4)
function process(data) {
if (data) {
if (data.isValid) {
return transform(data);
}
}
return null;
}
// After (Cognitive: 2)
function process(data) {
if (!data) return null;
if (!data.isValid) return null;
return transform(data);
}
Name your boolean expressions:
// Before
if (user.age >= 18 && user.hasLicense && !user.isSuspended) { ... }
// After
const canDrive = user.age >= 18 && user.hasLicense && !user.isSuspended;
if (canDrive) { ... }
Extract inner loops into separate functions with meaningful names.
Use early returns, switch statements, or lookup tables instead of nested if-else chains.
Cognitive complexity often correlates with but differs from cyclomatic complexity. A function with CC=10 but deep nesting may have cognitive complexity of 25. Stellarion reports both metrics because they capture different aspects of code quality.
For the complete metrics reference, see Stellarion Quality Metrics.
Code Quality Metrics Overview
Stellarion is an AI Powered Code Quality Platform that provides comprehensive code analysis across 10+ programming languages. It delivers real-time complexity metrics, quality scoring, and architectural insights to improve code maintainability and reduce technical debt.
Cyclomatic Complexity
Cyclomatic complexity (CC) measures the number of linearly independent paths through a program's source code. Developed by Thomas McCabe in 1976, it remains one of the most widely used metrics for assessing code testability and maintainability.