Case-logic

lex at cc.gatech.edu lex at cc.gatech.edu
Wed Oct 27 15:34:27 UTC 2004


Blake, the simple answer is to use a separate class per state.  Then
instead of a case statement, you can send messages to the current state
object and ask it to Do The Right Thing.  Since each state has a
different class, each one can have a separate doTheRightThing method,
and the normal OO method-binding machinery will hook up the
doTheRightThing *request* with the appropriate *response*.

To be fair, a lot of people do it the other way too, though, and use
symbols plus case statements.

I don't think both are fine in the right circumstances.  If you have
just a few states and only a few places that the state is checked, then
case statements plus symbols can give you shorter, simpler code;
converting the simple cases to use a class-per-case means that anyone
reading the code has to go tracing through the state classes all the
time.  On the other hand, if you check the state in a lot of places, or
if there are a lot of differernt states, then using first-class state
objects, each with their own class, can make the code simpler on the
whole.  In this latter case, readers cannot asborb all the different
states simultaneously anyway, so you may as well factor them out.

Finally, notice that separating out the states into separate objects,
may make it easier for you to think about what exactly a state is.  This
can make it easier to factor your state into multiple objects, thus
reducing the number of explicit states.  Having a lot of explicit,
discrete states seems like a recipe for confusion, so trying to minimize
them seems like a good idea.

Lex



More information about the Squeak-dev mailing list