switch

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Wed Dec 9 01:39:48 EST 2009


On Tue, 08 Dec 2009 21:36:23 -0800, Asun Friere wrote:

> 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.

That's a provocative statement.



> 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.

Perhaps that's true, but you'll note that the example given above doesn't 
run a single object through a series of tests, but runs a series of tests 
on DIFFERENT objects, to find the first which matches.

But putting that aside, I find myself wondering how you would deal with 
the following switch-like series of tests.


def print_grades(score):
    if not 0 <= score <= 100:
        raise ValueError("score must be between 0 and 100")
    if score < 50:
        print "You have failed."
        consider_suspension()
    elif score == 50:
        print "You have just passed by the skin of your teeth."
    elif score < 60:
        print "You have scored a D. You need to try harder."
    elif score < 70:
        print "You have scored a C."
    elif score < 80:
        print "You have scored a B. Well done."
    elif score < 100:
        print "Congratulations, you have scored an A."
    else:
        assert score == 100
        print "You have scored a PERFECT 100% SCORE!!!"
        if not evidence_of_cheating():
            call_newspapers()


Obviously that could, with a non-trivial amount of work, be turned into a 
dictionary dispatch, but is the benefit worth the extra effort?

 
> 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.

I don't see how a series of tests on a single object is comparable to the 
double-dispatch example given.



-- 
Steven



More information about the Python-list mailing list