[Tutor] switch vs table dispatch
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Fri Feb 4 20:15:51 CET 2005
On Fri, 4 Feb 2005, Smith, Jeff wrote:
> What you are try to do is "execute a block of code based on the value of
> a single statement." if/elif doesn't do that and thereby introduces the
> possibility of errors.
>
> switch on-this:
> case 'a':
> do something
> case 'b':
> do something else
> case 'c':
> do yet something else
>
> Is much clearer and more maintatinable than
>
> if on-this == 'a':
> do something
> elif on-this == 'b':
> do something else
> elif on-this == 'c':
> do yet something else
Hi Jeff,
if/elif chains like this can be improved by using a table-dispatch
technique:
### Python Pseudocode ###
def doActionA():
...
def doActionB():
...
def doActionC():
...
dispatchTable = { 'a' : doActionA,
'b' : doActionB,
'c' : doActionC }
dispatchTable[on_this]()
######
We perfectly agree with you about the hideousness of using if/elif/elif to
do a 'switch'-style control flow. But that's not the only tool in our
arsenal. *grin*
switch() in other languages like C or Java have other limitations that are
hard to explain to beginners. As one concrete example: we can't use a
string as the dispatch value in Java's switch. We're restricted to use
chars, bytes, shorts, or ints, due to the low-level implementation nature
of 'switch':
http://java.sun.com/docs/books/jls/second_edition/html/statements.doc.html#35518
(I believe the expression is used as an index into a jump table, which
limits it to something small and numeric.) Ultimately, this restricts the
use of 'switch' to simple dispatch tasks, and we can already handle those
nicely with a dictionary lookup.
Hope this helps!
More information about the Tutor
mailing list