State Transitions and Encapsulation
What you'll learn: You'll learn who controls state changes in the State pattern and how to properly hide state-specific data.
The Core Decision: Who Drives Transitions?
When implementing the State pattern, you must decide who triggers state transitions: the Context or the individual State objects themselves.
Context-controlled transitions: The Context object knows about all possible states and decides when to switch. This centralizes transition logic, making the overall state machine easy to understand at a glance. However, it couples the Context to all State classes.
State-controlled transitions: Each State object decides its own successor state based on conditions or actions. This decentralizes logic—each state is self-contained and knows only about states it can transition to. This approach better encapsulates state-specific transition rules but makes the overall flow harder to trace.
Think of it like a traffic light system: Should the control box (Context) manage all transitions based on timers? Or should each light state (Red, Yellow, Green) know what comes next and trigger its own change?
Encapsulating State-Specific Data
States often need data to function. Should this data live in the Context or within State objects?
Data in Context: If multiple states share data (like a counter or user input), store it in the Context and pass it to State methods. This keeps states stateless and reusable.
Data in State objects: If data is truly specific to one state, encapsulate it within that State class. This prevents pollution of the Context with specialized fields.
Most implementations use a hybrid: shared data in Context, state-specific data in State objects.
Key Takeaway: Choose Context-controlled transitions for centralized clarity or State-controlled transitions for better encapsulation; store shared data in Context and state-specific data within State objects to maintain clean separation of concerns.