does a switch idiom make sense in this case?
- by the ungoverned
I'm writing a parser/handler for a network protocol; the protocol is predefined and I am writing an adapter, in python.
In the process of decoding the incoming messages, I've been considering using the idiom I've seen suggested elsewhere for "switch" in python: use a hash table whose keys are the field you want to match on (a string in this case) and whose values are callable expressions:
self.switchTab = { 'N': self.handleN,
'M': self.handleM,
...
}
Where self.handleN, etc., are methods on the current class.
The actual switch looks like this:
self.switchTab[selector]()
According to some profiling I've done with cProfile (and Python 2.5.2) this is actually a little bit faster than a chain of if..elif... statements.
My question is, do folks think this is a reasonable choice? I can't imagine that re-framing this in terms of objects and polymorphism would be as fast, and I think the code looks reasonably clear to a reader.