Monday, April 11, 2005

Dispatch Tables in Python

I mentioned dispatch tables last time around. Dispatch tables are basically dictionaries of functions. Here's a concrete if trivial example of how to use them, written in Python.


class Document:
def __init__(self):
self.dtable = {
"color": Document.setColor,
"text": Document.addText
}
def setColor(self, rgb):
# set the pen colour for the document
pass
def addText(self, text):
# add some text to the document
pass
def loadXml(self, node):
while node:
self.dtable[node.nodeName](self, node.data)
node = node.nextSibling


As you can see, the loadXml function itself knows nothing about what XML nodes might occur, or what functions must handle them. This is important because it allows code to handle new nodes (or change the handling of old nodes) to be added in, say, a subclass without changing the original class at all. All that is needed is to modify the dispatch table (dtable). This is a powerful technique, and much used in Lisp and C. It has several advantages over a more conventional if-then-else approach:


  • It's more elegant. In most languages (with the curious exception of Java), this technique takes less lines of code and is easier to work with. Fewer lines of code equals fewer mistakes.

  • It's more robust. A mistake in one case won't topple the other cases. There is more separation between the handlers for various types than with some other techniques; also, the dispatch mechanism need know nothing specific about the handlers.

  • It's future-proof. The mapping of metadata to interpretation is independent, in most cases, of the dispatch mechanism. Changes to input data formats, for example, can be handled with minimal intrusions into existing code.

  • It's faster. Surprised? A dictionary look-up is ideally O(1); a chain of ifs is O(n).

3 Comments:

Anonymous Anonymous said...

I was suggesteԁ thіs web ѕitе by my сοusin.
Ι'm not sure whether this post is written by him as no one else know such detailed about my trouble. You're wonderful!
Τhаnks!

Ѕtop by my ωeb pаgе igrice online decije

6:46 PM  
Anonymous Anonymous said...

I was suggested this web site by my cousin. I'm not sure whether this post is written by him as nobody else know such detailed about my difficulty. You are wonderful! Thanks!

Look at my page - homepage here

8:46 AM  
Anonymous Anonymous said...

Hello There. I found your blog using msn. This is a
very well written article. I will make sure to bookmark
it and come back to read more of your useful info. Thanks for the post.
I will certainly comeback.

Here is my webpage - psoriasis treatment cream

2:59 PM  

Post a Comment

<< Home