State Pattern vs Conditional Logic
You'll learn when to replace messy conditionals with the State pattern and when simpler approaches are better.
The Decision Point
Not every situation with state-based behavior requires the State pattern. Sometimes a simple if statement or switch is clearer and more maintainable. The key is recognizing when conditional logic becomes a liability rather than a solution.
When Conditionals Become Problematic
Imagine a document approval workflow with 5 states and 8 possible actions. With conditionals, you'll have if or switch statements scattered across multiple methods, each checking the current state:
function approve() {
if (state is Draft) { /* logic */ }
else if (state is Pending) { /* logic */ }
else if (state is Review) { /* logic */ }
// ...
}
function reject() {
if (state is Draft) { /* logic */ }
else if (state is Pending) { /* logic */ }
// same checks again...
}
Adding a new state means modifying every method. Adding a new action means considering every state.
When State Pattern Shines
Use State pattern when:
- You have many states (typically 4+) with different behaviors
- State-specific logic is complex and scattered
- Adding new states is likely (system will evolve)
- Transitions have intricate rules that benefit from encapsulation
When Simpler Approaches Suffice
Stick with conditionals when:
- You have 2-3 simple states with minimal logic
- State behavior is truly trivial (one or two lines)
- The system is stable and unlikely to add states
- The conditional is localized to one small method
Key Takeaway: Choose State pattern when state-based conditionals proliferate across multiple methods and complexity grows; prefer simple conditionals for straightforward, stable scenarios with few states.