[Tutor] Are you allowed to shoot camels? [kinda OT]
Smith, Jeff
jsmith at medplus.com
Fri Feb 4 22:55:53 CET 2005
Now who's joking? Are you saying that
switch var:
case 'a':
print 'a'
case 'b' or 'c':
print 'b or c'
case 'd':
pass
default:
print 'default case'
Is less clear and maintainable than
def do_this_function():
print 'a'
def do_that_function():
print 'b or c'
def do_pass_function():
pass
def do_default_function():
print 'default case'
ftable = { 'a' : do_this_function,
'b' : do_that_function,
'c' : do_that_function,
'd' : do_pass_function }
ftable.get(var, do_default_function)()
Ugh!
-----Original Message-----
From: Alan Gauld [mailto:alan.gauld at freenet.co.uk]
Sent: Friday, February 04, 2005 1:14 PM
To: Smith, Jeff; Jacob S.; Nicholas.Montpetit at deluxe.com;
tutor at python.org
Subject: Re: [Tutor] Are you allowed to shoot camels? [kinda OT]
> 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.
In that case the best solution is a dictionary jump table.
That is more maintainable than either and much faster too.
And its also shorter to write.
[Especially with lambdas :-)]
> Note that the logic intended is that "on-this." So why force the
> programmer to rewrite it N times and thereby introduce the
possibility
> of N-1 typographical errors...
Thats a fair point although the dictionary solution avoids that. OTOH
such switches tend to proliferate thropugh code and become a big source
of maintenance headaches in their own right - multiple update syndrome
across multiple files potentially.
> Note that I've left out break. I'm not convinced that fall-through is
> an important feature in switch and is usually the culpit in the cases
> of abuse.
The problem is its so hard to tell when fall though is happening
intentionally or by accident because someone forgot a break sytatement.
But when it comes to abuuse the fall through mechanism is one of the
worst offenders in C, its just too tempting to be "clever" with it.
> This is also true for the ternary operator. The desired logic is to
> assign the value of a variable based on the value of some other
> variable.
But its not its based on the value of an *expression*. If the test could
be limited to a single valiable value it might be justified but its an
arbitrary expression. That makes it a conditional statement, which is
most clearly represented by an if/else... Well I think so :-)
> I also like Perl's unless statement but really prefer
> VBs DO/WHILE/UNTIL/LOOP constuct. Nothing beats it for clarity of
> expression.
I won't argue on either point, Python's minimalist
approach - there's only one way to do it - means a
paucity of looping constructs - something I point
out in my tutorial. But I can live with it for the
other niceties it brings.
Alan G.
More information about the Tutor
mailing list