Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does state pattern accurately represent the approach?

What I gather from typical implementation of State patterns is this:

Problem: Represent an object O, whose behavior alters based on its current state.
Solution:
1. Let S, another object inside this object O, represent state
2. The object S will invoke the appropriate operation of O
3. The object S will decide the next state for the object O

My concern is primarily with #3. The state transition table is essentially spread across all the states. I have seen these solutions become cumbersome to manage very quickly. Instead of being indicator, these states hold too much information about the state machine.
Even though #2 bothers me, I guess it is fairly reasonable (Moore machine.) The only issue I have seen arises during bug fixing/debugging: code navigation/understanding becomes difficult until one commits all the state mappings to memory.

Would the following implementation be more precise?
Represent states as enumerations, and the object decides the action based on the value held by the enumeration. The state transitions are in a table (δ, a state transition function) that is a map of current state to next state. This state transition table also holds the action to be performed (Mealy machine)

like image 783
CMR Avatar asked Mar 07 '11 16:03

CMR


1 Answers

I don't know why you suppose that the State pattern can only represent Moore machines.

void SleepingState::alarm()
{
    kick_alarm_clock();
    set_state(new GrumpyState());
}

We chose our output (kick_alarm_clock) based on both the state (SleepingState) and the event (alarm), which makes it a Mealy machine.

Your alternative is indeed valid and popular (and there are others). Since several approaches are all sufficient to implement the machine logic, you make the decision based on other considerations of 'design' or personal taste. Design reasons to prefer the State pattern might be if you think you will often be adding new states, or if some states seem similar enough to warrant an inheritance relationship. I tend to choose on aesthetics: I use the State pattern only if the machine is fairly dense - i.e. there are nontrivial actions & transitions for most { state, event } pairs. If the machine is fairly sparse, I get embarrassed by all the empty methods.

like image 131
fizzer Avatar answered Oct 09 '22 21:10

fizzer