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")
state diagram in system design?A to state B on event start in a state diagram?A -> B : event.Idle -> Processing : start
Processing -> Idle : stop
Processing -> Error : fail
Processing and receives the fail event?Processing state and receives fail event.Processing, on fail, the transition goes to Error.Start -> Running : begin
Running -> Paused : pause
Paused -> Running pause
State1 -> State2 : event.Paused -> Running pause missing the colon before pause.Idle, Selecting, Dispensing, and OutOfStock. Which transition should be added to handle the event stockEmpty when the machine is in Idle?stockEmpty means no items are left to dispense.Idle and stock is empty, it should move to OutOfStock state.Pass the test and this pattern moves unknown