Brain Method
Function Strategy | Multi-metric
A function that has become the cognitive centre of a component — too long to skim, too complex to reason about, and too deeply nested to modify safely.
Detection Rule
SLOC > 65 AND CC > 5 AND max_nesting > 3
| Metric | Threshold | Meaning when exceeded |
|---|---|---|
| CC | > 5 | Multiple independent code paths — non-trivial logic |
| SLOC | > 65 | Too long to read in a single glance |
| max_nesting | > 3 | Deeply nested control flow — hard to follow mental stack |
Note: The nesting metric here uses max_nesting (maximum control-flow depth), and the length uses SLOC (source lines of code — blank lines and comments excluded), not raw LOC.
TypeScript Example
function processPayment(req: PaymentRequest): PaymentResult {
// 80 SLOC, CC=9, max_nesting=5 → Brain Method
if (req.type === "card") {
for (const item of req.items) {
if (item.taxable) {
if (item.country === "US") {
if (item.state === "CA") {
// depth 5 ← exceeds threshold
}
}
}
}
}
// ... 60 more lines
}
Remediation
- Extract Method — pull inner blocks (especially inside deep nesting) into well-named helper functions.
- Replace conditional with polymorphism — large
if/elsetrees often indicate missing dispatch. - Early return / guard clauses — invert conditions to reduce nesting depth quickly.
- Aim for each function to fit on a single screen (< 40 SLOC) with CC ≤ 5.
Related strategies
Related metrics
Cyclomatic Complexity · Maintainability Index · Technical Debt