Skip to content

no-excessive-cognitive-complexity

Error on cognitive complexity above 20; scores up to 20 pass.

Why

Nested control flow increases the context a reader must retain while following a function.

Fix

Examples are fictional and written for this documentation; domain types are omitted. The library example replaces nested eligibility checks with early returns while preserving evaluation order. Refactor one function at a time, starting with its largest contributors. First simplify control flow and reduce nesting within the function. Extract a helper only when it clarifies a cohesive responsibility or enables meaningful reuse; do not split code solely to lower the score. Use lookup tables only for equivalent pure dispatch. Preserve APIs, side effects, evaluation order, and exception behavior. Run relevant tests before and after; remeasure the original and extracted functions. Do not hide branches in dense expressions or add indirection just to lower a score.

Examples

Before — flagged Six nested decisions require a review
src/decision.py
def decide(a, b, c, d, e, f):
if a:
if b:
if c:
if d:
if e:
if f:
act()
After — preferred Guard clauses reduce nesting
src/decision.py
def decide(a, b, c, d, e, f):
if not a:
return
if not b:
return
if not c:
return
if not d:
return
if not e:
return
if not f:
return
act()
Before — flagged Synthetic library eligibility before: score 28
src/library.py
def can_borrow(member, book):
if member.active:
if member.email_verified:
if not member.suspended:
if member.balance == 0:
if member.borrowed_count < 5:
if book.available:
if not book.reference_only:
return True
return False
After — preferred Synthetic library eligibility after: score 7
src/library.py
def can_borrow(member, book):
if not member.active:
return False
if not member.email_verified:
return False
if member.suspended:
return False
if not (member.balance == 0):
return False
if not (member.borrowed_count < 5):
return False
if not book.available:
return False
if book.reference_only:
return False
return True