Using a switch-like if/else construct versus a dictionary?
Duncan Booth
duncan.booth at invalid.invalid
Wed Jun 20 04:07:30 EDT 2007
asincero <asincero at gmail.com> wrote:
> handle_case = {}
> handle_case[1] = doCase1()
> handle_case[2] = doCase2()
> handle_case[3] = doCase3()
> handle_case[4] = doCase4()
> handle_case[5] = doCase5()
> handle_case[c]()
>
If the switch values are simple integers then a list would be a more
obvious choice:
handle_case = [ doCase1, doCase2, doCase3, doCase4, doCase5 ]
handle_case[c-1]()
> Note that in this situation using OO polymorphism instead of a switch-
> like construct wouldn't be applicable, or at least I can't see how it
> could be.
That is often the case when you reduce your question to a mickeymouse do
nothing example.
There are many ways to write code that could be written using a switch
statement. If you took a few real use-cases then you would probably each
one needs a different technique for best effect depending on the number
of different cases, the values which must be accessed within each case,
the side-effects (if any) expected from handling the case etc.
The obvious options include: if/elif chain; a list or dictionary
containing data values (not functions); a list or dict containing
functions; command pattern (i.e. a class with a dispatch method); a
class hierarchy and polymorphism; visitor pattern.
For an example of the last of these see
http://www.chris-lamb.co.uk/blog/2006/12/08/visitor-pattern-in-python/
which uses decorators to produce a very clean implementation using (I
think) PyProtocols dispatch.
More information about the Python-list
mailing list