What does "high cyclomatic complexity" mean?
It means your code has turned into a labyrinth, and anyone trying to maintain it will likely curse your name.
Cyclomatic complexity is a metric that counts the number of independent paths through your code. Think of it as a "how many ways can I break my brain" counter. The higher the number, the more branches, loops, and conditionals are cluttering up your code.
- Low cyclomatic complexity (1–10): Code is simple, readable, and probably written by someone who still has hope.
- High cyclomatic complexity (20+): Code is a minefield of
ifstatements,whileloops, and spaghetti logic.
In short, “high cyclomatic complexity” means your code is doing too much in one place and needs to be refactored into smaller, cleaner chunks.
Checklist: How to Reduce Cyclomatic Complexity
✅ 1. Split Large Functions
Break big functions into smaller, focused ones.
def process_order(order):
if order.type == 'online':
...
elif order.type == 'in-store':
...
# Better:
def process_order(order):
if order.type == 'online':
handle_online(order)
elif order.type == 'in-store':
handle_instore(order)
✅ 2. Replace Complex Conditionals with Polymorphism
# Bad:
if shape == 'circle':
...
elif shape == 'square':
...
# Better:
class Shape:
def area(self): pass
class Circle(Shape):
def area(self): return pi * r * r
✅ 3. Use Guard Clauses
# Instead of:
def process(user):
if user.is_active:
if user.has_permission:
...
# Do:
def process(user):
if not user.is_active or not user.has_permission:
return
...
✅ 4. Use Lookups Instead of Conditionals
# Instead of:
if key == 'a': do_a()
elif key == 'b': do_b()
# Do:
actions = {'a': do_a, 'b': do_b}
actions.get(key, do_default)()
✅ 5. Extract Logic from Loops
# Instead of:
for item in items:
if item.is_valid() and not item.is_expired():
if item.value > threshold:
...
# Do:
for item in items:
handle_item(item)
✅ 6. Minimize Boolean Logic
# Instead of:
if not (x or (y and not z)):
# Do:
should_skip = x or (y and not z)
if not should_skip:
Code copied!