Problem Statement
When software components have complex behaviors that depend on many conditions, it becomes hard to track all possible states and transitions. This confusion leads to bugs, unexpected behavior, and difficulty in maintenance.
┌───────────┐ event1 ┌───────────┐
│ State A │ ───────────────▶ │ State B │
└───────────┘ └───────────┘
▲ │
│ event2 │ event3
└──────────────────────────────┘
This diagram shows two states, A and B, with arrows representing events that cause transitions between them.
### Before: No clear state management class Door: def __init__(self): self.is_open = False def open(self): if not self.is_open: print("Door opened") self.is_open = True def close(self): if self.is_open: print("Door closed") self.is_open = False ### After: Using state pattern with explicit states from enum import Enum class DoorState(Enum): CLOSED = 1 OPEN = 2 class Door: def __init__(self): self.state = DoorState.CLOSED def open(self): if self.state == DoorState.CLOSED: print("Door opened") self.state = DoorState.OPEN else: print("Door is already open") def close(self): if self.state == DoorState.OPEN: print("Door closed") self.state = DoorState.CLOSED else: print("Door is already closed")