3 ms·
Case statements are an anti-pattern. The proper way to implement that design pattern is using either dispatch dictionaries or plain-old polymorphism.
by bjourne 6y ago
Case statements are an anti-pattern. The proper way to implement that design pattern is using either dispatch dictionaries or plain-old polymorphism.
- hnlmorg 6y agoI see. Are you able to provide an example?
- bjourne 6y agoSuppose you are dispatching on token types. You could write something like this: handlers = {'start' : handle_start, 'jump' : handle_jump, 'end' : handle_end, ...} for tok, arg in tokens: if tok not in handlers: raise ValueError('Wrong token type, must be any of %s.' % ', '.join(handlers)) handlers[tok](arg)
- hnlmorg 6y agoI see, I do follow that design pattern for larger switch statements or where the dictionary had to be dynamically populated (even in non-Python languages) but I hadn't considered using it for smaller switch statements as well. Thank you for the example.