Use when reducing cognitive complexity, flattening nested code, or simplifying functions. Triggers on "reduce complexity", "simplify", "too nested".
Refactor functions to reduce cognitive complexity score while maintaining identical behavior.
/complexity [file:function]
Examples:
/complexity # Analyze current diff
/complexity services/analyst/core/query.py # Analyze specific file
/complexity query.py:process_result # Analyze specific function
What increments complexity (+1 each):
if, else if, else, ternary operatorsforforeachwhiledo whilecatchswitch, casegoto, break, continue (labeled)&&, || in conditionsNesting multiplier:
What's free (no increment):
Target: Keep cognitive complexity under 15 per function
# Before: Complexity 6
def calculate(data):
if data is not None: # +1
total = 0
for item in data: # +1 +1 (nested)
if item > 0: # +1 +2 (nested)
total += item * 2
return total
# After: Complexity 4
def calculate(data):
if data is None: # +1
return None
total = 0
for item in data: # +1
if item > 0: # +1 +1 (nested)
total += item * 2
return total
# Before: Complexity 5
def process_eligible_users(users):
for user in users: # +1
if ((user.is_active and # +1 +1 +1 +1
user.has_profile) or
user.age > 18):
user.process()
# After: Complexity 3
def process_eligible_users(users):
for user in users: # +1
if is_eligible_user(user): # +1 +1
user.process()
def is_eligible_user(user):
return (user.is_active and user.has_profile) or user.age > 18
Extract logical blocks into separate functions with single responsibilities.
Analyze the target function:
Preserve existing tests - understand coverage before changes
Refactor using strategies above:
Verify behavior - run existing tests
Add tests if needed - for new helper functions with complex logic