Last night, I felt it was high time I learned some
Python,
since it's been around for years and since Eric S Raymond recommends it as a first
language, it can't bee too hard to pick up for a grizzly old git like me.
Now, while I can do things in three lines of python that would take several pages
to do in C (which is pretty much the raison d'etre for any high level language),
one thing struck me as being slightly odd - there's no
switch statement. (The
DBA weenies among you will know this as the SELECT CASE statement - it's the same
animal). So you can't do things like:
switch( viking ) {
case 1 :
menu = "eggs";
break;
case 2 :
menu = "bacon";
break;
default :
menu = "spam";
break;
}
(At this point, all of you python lovers out there are saying : "Eggs? Bacon?
Spam? You really have been drinking the python kool-aid haven't you?"
Shut up.)
And this doesn't actually strike me as a bad thing. Why's that? Well,
switch is easy to abuse. Here's a popular example :
switch( type ) {
case sprocket :
DoSprocketThing();
break;
case widget :
DoWidgetThing();
break;
}
What's wrong with this? Well basically, when you add a new type, like a grommit,
you've got to plumb your
DoGrommitThing into the switch block. And what
are we doing here? Calling a different method depending on what type we've got? Hmm,
smells like polymorphism to me. Call the object oriented police!
And that example's a nice one. I've seen much worse, like where you don't
just have one function call, but great steaming piles of code in each
case block. Home baked state machine handlers are the biggest offenders for
this. (Especially if they're written in VB. With nested With statements.
Can you tell I've had to debug a few of these in the past?)
Anyway, python works around the lack of a switch by allowing you to associate values
with functions. Pop onto the wikipedia page above and you'll see an example. I like
this, because you're abstracting away the algorithm to do the switch as a data
structure. C's been doing this for years (with function pointers), but the nice thing
about python is it makes this easy, and doing silly stuff hard. I mean, you can
still do insane state machine abuse by using lambdas though, just it's just a bit
harder to think about what code to write, so you're less likely to do it.
I don't miss switch. Do you?