switch

Asun Friere afriere at yahoo.co.uk
Wed Dec 9 00:36:23 EST 2009


On Dec 9, 4:02 pm, Kee Nethery <k... at kagi.com> wrote:
> I string together a bunch of elif statements to simulate a switch
>
> if foo == True:
>         blah
> elif bar == True:
>         blah blah
> elif bar == False:
>         blarg
> elif ....


This code is probably symptomatic of poor design. (Not to mention that
your condition tests).  For which reason python has no 'case'
statement and why no decent OO language should.

It is a principle of OO design that "an object should know what to do
itself."  Rather running an object though a series of tests, it is
better to send the object a message, relying on polymorphism or duck-
typing, and deal with any exceptions thrown.

Generally if you find yourself wanting to use a 'case' statement or
writing a series of if/elif which involves more than say, three,
elifs, condsider whether you cannot use a <a href="http://
peak.telecommunity.com/protocol_ref/dispatch-example.html">double
dispatch</a> mechanism instead.




More information about the Python-list mailing list