Thursday, March 03, 2005

Python and VB

So I'm working on a project where VB.NET is mandated by the customer. The reason, presumably, is that it's dead easy to drag any poor schmuck off the streets and have him churn out VB code for minimum wage.

Leaving the short-sightedness of this aside, I'd like to talk about what a shock it was having to write VB code after having spent some glorious months in Python. To cut to the chase, and without wishing to wallow in warrantless waffle, the kind of shock that it was was this: bad.

Compare, cherished chums, certain canonical code cases:

' VB
Dim doc As new System.Xml.XmlDocument
doc.Load ("test.xml")
Dim pages As System.Xml.XmlNodeList
pages = doc.GetElementsByTagName ("page")
If pages.Count <> 1 Then
throw new Exception ("Invalid XML")
End If
Me.images = new System.Collections.ArrayList
Dim imgentry As System.Xml.XmlNode
Dim attr As System.Xml.XmlNode
For Each imgentry In pages(0).ChildNodes
If imgentry.Name = "image" Then
Dim imginfo As New ImageInfo
For Each attr In imgentry.ChildNodes
If Attr.Name = "title" Then
imginfo.title = Attr.FirstChild.Value
End If
If Attr.Name = "filename" Then
imginfo.filename = Attr.FirstChild.Value
End If
End If

# Python
from xml.dom import minidom
doc = dom.parse("test.xml")
pages = doc.getElementsByTagName("page")
if len(pages) != 1:
raise Exception, "Invalid XML"
self.images = []
for imgentry in pages[0].childNodes:
if imgentry.nodeName == "image":
imginfo = ImageInfo()
for attr in imgentry.childNodes:
if attr == "title":
imginfo.title = attr.firstChild.nodeValue
if attr == "filename":
imginfo.filename = attr.firstChild.nodeValue

Now, if anything, this example is a little unfair to Python. Why? Because a reasonable Python programmer would take one look at the code above, laugh his ass off and rewrite it with a dispatch table and list comprehension. The same approach would, I'm fairly confident, double the number of lines of VB code required, while halving the number of Python lines.

By the way, a dispatch table is a far more robust solution to the above problem. I might discuss them in a future post, although there's plenty of reference material out there on the web.

At any rate, it should be evident from the above that even a literal translation of VB code into Python results in substantial savings in lines of code, and therefore in time and errors. Don't even start with the dynamic-versus-static-typing debate: the fact is that the end result is largely the same in both cases, and the work required differs substantially in favour of Python. In my pragmatic little book, that's QED.


Post a Comment

<< Home