Bird
0
0
LLDsystem_design~3 mins

Why State pattern in LLD? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a simple design trick can turn your tangled state logic into clean, manageable code!

The Scenario

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.

The Problem

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 Solution

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.

Before vs After
Before
if(state == 'Idle') { if(moneyInserted) state = 'HasMoney'; } else if(state == 'HasMoney') { if(selectItem) state = 'Dispensing'; }
After
state.handleMoneyInserted(); // state object changes itself internally
What It Enables

It enables building flexible systems where adding or changing states is simple and safe without breaking existing code.

Real Life Example

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.

Key Takeaways

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.