Working around a lack of 'goto' in python
Roy Smith
roy at panix.com
Sun Mar 7 15:49:07 EST 2004
Stephen Horne <steve at ninereeds.fsnet.co.uk> wrote:
>> goto allows the code for a state to be fallen into from the top.
>
> How is this different to the more typical switch-within-loop method?
Not much. The C switch statement isn't much better than a goto, for
just that reason :-)
> returning a function pointer to a
> function that is immediately going to call that function pointer,
> you're basically just faking the effect of a goto anyway.
In some respects, you're right. Certainly, both ways get you the same
pseudo-random flow of control, but that's inherent in a state machine.
What the function-per-state approach gets you is modularity. Each
function at least has its own namespace and set of local variables.
To tie this in with the current thread on unit testing, it's also a lot
easier to test a bunch of little functions than a collection of gotos.
You said:
> In fact its basically a special case of the state variable method,
> using the processors IP as the state variable.
That's a very good observation. Imagine you implemented your state
machine with gotos. To test each transition, you need to get the
machine into the right state before each test by feeding it a sequence
of inputs which navigates your state graph in the right way. That's
complicated and error prone to design (the last thing you want is an
error-prone test procedure). If there were many states and edges, it
would be very slow. If the state machine is non-deterministic (timing
dependencies, perhaps), it would be impossible.
Of course, this is all assuming that the logic implemented in each state
is different enough to require writing individual functions. Some state
machines (like those that execute compiled regular expressions) are
simple enough to be table driven. With a tabular approach, you get the
same testability you do with the functional approach; you can set the
machine to any random state, apply a single input, and see what happens.
You can't do that with gotos because the state is stored in a place
that's not exposed at the language level (unless you're writing in
assembler).
More information about the Python-list
mailing list