Code Readability Metrics
TL;DR
Readability can be measured — cyclomatic complexity, cognitive complexity (SonarQube), lines per function, parameter count, and nesting depth are all quantifiable proxies for readability.
Explanation
Key metrics: Cyclomatic Complexity (CC) — control flow paths. Cognitive Complexity (CC2, SonarQube) — mental effort to understand, penalises nesting more than CC. Lines of Code per function (LOC) — under 20 is ideal. Parameter count — under 4 parameters. Nesting depth — under 3 levels. Halstead metrics — volume, difficulty, effort. Maintainability Index (0–100, VS Code, Visual Studio) — composite metric. Tools: PHPStan (complexity), PHPMD, SonarQube, CodeClimate, phploc (PHP Lines of Code). These are guides, not absolute rules — context matters.
Common Misconception
✗ Low metrics always mean readable code — a function with low complexity but cryptic variable names is still unreadable. Metrics are proxies, not guarantees.
Why It Matters
Measurable metrics enable objective code review discussions and track codebase health over time — preventing the gradual degradation of readability.
Common Mistakes
- Optimising for metrics rather than readability — gaming CC by moving code into helper functions that don't improve clarity.
- Treating metrics as hard limits rather than signals for review.
- Not setting baseline metrics for a codebase and tracking change over time.
Code Examples
✗ Vulnerable
// High CC, high nesting, short but unreadable:
function p($u,$a){if($u&&$a){if($u->r>0){if($a<100){return $u->r*$a;}}}return 0;}
✓ Fixed
function calculateDiscount(User $user, float $orderAmount): float {
if (!$user || $orderAmount <= 0) return 0.0;
if (!$user->hasActiveDiscount()) return 0.0;
return $user->discountRate * $orderAmount;
}
References
Tags
🤝 Adopt this term
£79/year · your link shown here
Added
23 Mar 2026
Views
25
🤖 AI Guestbook educational data only
|
|
Last 30 days
Agents 0
No pings yet today
No pings yesterday
Amazonbot 8
Perplexity 4
Unknown AI 3
Google 2
Ahrefs 2
ChatGPT 1
Meta AI 1
Also referenced
How they use it
crawler 19
pre-tracking 2
Related categories
⚡
DEV INTEL
Tools & Severity
🟢 Low
⚙ Fix effort: Low
⚡ Quick Fix
Set PHPMD/SonarQube rules for CC>10, LOC>50, params>4. Run in CI. Use cognitive complexity (SonarQube) as a more human-centred metric. Track trends, not just point values.
📦 Applies To
web
cli
queue-worker
🔗 Prerequisites
🔍 Detection Hints
Auto-detectable:
✓ Yes
phpmd
phploc
sonarqube
codeclimate
⚠ Related Problems
🤖 AI Agent
Confidence: Low
False Positives: High
✗ Manual fix
Fix: High
Context: File