[Tutor] Are you allowed to shoot camels? [kinda OT]

Alan Gauld alan.gauld at freenet.co.uk
Sat Feb 5 00:39:10 CET 2005

> Now who's joking?  


> Are you saying that 
> switch var:
> case 'a':
>    print 'a'
> ...
> default:
>    print 'default case'
> Is less clear and maintainable than

I don;tthink I said (certainly didn't mean) less clear, but 
yes it is less maintainable.

But then...

> def do_this_function():
> print 'a'

> ....
> ftable = { 'a' : do_this_function,
>            'b' : do_that_function,
>            'c' : do_that_function,
>            'd' : do_pass_function }
> ftable.get(var, do_default_function)()

I did also say that it was best with proper lambdas

ftable = {'a' : lambda: print 'a',
          'b' : lambda: print 'b'

and I'd code the calling section:

try: ftable[value]()
except KeyError: doDefaultFunction()

Its more maintainable because even if the switches proliferates 
as they tend to do, the dictionary stays in one place and the 
calling code never needs changing. So the changes are much 
more localised. And of course the more complex the case 
actions are, the more effective the dictionary/function 
approach becomes.

Alan G.

More information about the Tutor mailing list