Hi,
I am trying to evaluate the tradeoff between the traditional procedural type of state machine implementation vs. OO state machine implementation.
While the OO state
pattern is more elegant(better abstraction on what needs to be done for each state) and easier for state classes to be reused, the drawback I see is that the OO way could potentially create/destroy way more objects (Performance!) than the traditional way.
e.g.
Traditional way:
class State {
boolean aReady;
boolean bReady;
boolean cReady;
}
void processEvent(State st) {
if (st.aReady && st.bReady && cReady)
// handle logic
else if (st.aReady && st.bReady && !cReady)
// handle logic
... etc
}
- Here, the logic of processEvent could be messy but you would only have one state object at runtime.
OO state machine:
class A_B_C_State implements State {
public State processEvent();
}
class A_B_NC_State implements State {
public State processEvent();
}
class A_NB_C_State implements State {
public State processEvent();
}
class A_NB_NC_State implements State {
public State processEvent();
}
...etc.
Here, there are 9 classes, each time you change state, a new state object needs to be instantiated and the old state object garbage collected. Although code structure is more elegant, performance hit is huge (esp in a server runtime environment with state changing for each client request).
I would greatly appreciate any inputs or pointers to documents about how to achieve a good balance between them.
Thanks