Skip to main content

Excessive Branching

Description

What does it look like?

  • Excessive use of if / else if / switch makes the code hard to read
  • Logic for handling conditions is duplicated in multiple places
  • As conditions increase, it becomes a breeding ground for bugs and decreases maintainability

Why is it a problem?

  • Requires reviewing all conditions during modifications
  • Single functions or classes become bloated with responsibility
  • Difficult to unit test due to tightly coupled conditional logic
  • Hard to extend (violates the Open/Closed Principle)

Bad Example of the Anti-pattern

function calculatePrice(userType: string, basePrice: number): number {
if (userType === "student") {
return basePrice * 0.8;
} else if (userType === "member") {
return basePrice * 0.9;
} else if (userType === "vip") {
return basePrice * 0.7;
} else {
return basePrice;
}
}

Issues:

  • As if/else blocks accumulate, readability, testability, and the risk of bugs increase
  • Every time a new userType is introduced, the function body must be edited—making safe extension difficult
  • Discount logic is embedded directly, making it hard to reuse or centralize

Refactoring by Pattern

Design patterns that can address this

PatternOverviewMain Refactoring Approach
StrategyExtract conditional behaviorAllows behavior to be swapped at runtime
StateMap each state to its own behaviorLet state objects encapsulate condition logic
CommandEncapsulate each condition as a commandEnables recording and undoing actions
Chain of ResponsibilityPass responsibility through a chainExpress conditions as a natural flow
InterpreterParse and evaluate structured rulesSeparate complex condition logic as a domain grammar