Dispatch Tables in Python

We are assigning each function to a key we find convenient, in this case the result of the weekday() method on Date objects, then we use the dispatch dictionary to retrieve the object associated to the function and then ask Python to execute the function by appending the ().This kind of approach is way more desirable for a bunch of important reasons:Less and cleaner code, more readable and no need to add a long set of if-elif statements.Code is way more robust..The handlers for the various type are properly separated..The whole dispatch mechanism doesn’t need to know anything specific about the handlers.As a direct consequence of the previous point, the dispatch mechanism is independent from the code using it..Although it’s probably not the case for our specific example, if you need to enable more functions or disable existing ones, you just need a small change to the dispatch dictionary without altering the logic itself..This loose coupling is often a desirable design pattern in software engineering.Like a cherry on top, you are converting an O(n) algorithm to O(1)..Dictionaries are hash tables in Python, so the look-up process takes a constant time, while the if-elif compound need a linear scan across the whole set of statements.. More details

Leave a Reply