Discover how a simple design trick can turn your tangled state logic into clean, manageable code!
Why State pattern in LLD? - Purpose & Use Cases
Imagine you are building a vending machine that can be in different states like 'Idle', 'HasMoney', 'Dispensing', or 'OutOfStock'. You try to handle all these states using many if-else or switch-case statements scattered everywhere in your code.
This manual approach quickly becomes messy and hard to maintain. Adding a new state means changing many places, increasing bugs and confusion. It's like juggling too many balls at once and dropping them often.
The State pattern organizes each state into its own class with clear behavior. The vending machine just delegates actions to the current state object. This keeps code clean, easy to extend, and reduces errors.
if(state == 'Idle') { if(moneyInserted) state = 'HasMoney'; } else if(state == 'HasMoney') { if(selectItem) state = 'Dispensing'; }
state.handleMoneyInserted(); // state object changes itself internally
It enables building flexible systems where adding or changing states is simple and safe without breaking existing code.
Think of a music player app that changes behavior when playing, paused, or stopped. Using the State pattern, each mode handles play, pause, or stop commands differently without complex condition checks.
Manual state handling leads to complex, error-prone code.
State pattern encapsulates state-specific behavior in separate classes.
It makes systems easier to extend and maintain.
