Thursday, June 29, 2006

Emitting Code, Mind Your Language


Caught sight of a post over at Jeff Atwood's Coding Horror blog in which he demonstrates some of the clunkiness of using object libraries while coding. His example is as follows:

Let's say you wanted to generate and render this XML fragment:

<status code="1"><data><usergroup id="usr"></data>

He then shows the 17 or so lines of code it takes to do it with System.Xml objects and shows an alternative with Response.Write and a String formatter:

string s = @"<status code=""><data><usergroup id=""></data>";
Response.Write(String.Format(s, myCode, myUserGroup));

What he was getting at seemed fairly intuitive but a firestorm erupted over his berating those who considered the use of Response.Write and other more terse approaches over object models as second class or "dreadful citizenry."

Of course the big pitfall of his example is that it can be easily broken if the variables used in a Response.Write approach to generating xml contain unescaped or "bad" charactes. The object proponents jumped on this and hammered at how stuff like this works for a "trivial" example but it leaves an aweful exposure for "real world" applications. I'm always annoyed by that word "trivial" because those that use it tend to abuse it for the sake of complexity and overengineering. On the other hand, if you look at my previous post, I'm no stranger to bad characters and encoding issues (trust me, the pain has been dealt!). But I think what this discussion points to is something that is near and dear to my heart: language itself.

It didn't take long for a Ruby coder to point out that generating something like this in Ruby, using the libraries was as simple as:

builder =>STDOUT, :indent=>2)
builder.person { |b|"Jim");"555-1234") }

Which generates:


And along came a Perl programmer who shows the original example as:

$x = XML('status', [code => 1],
['data', [],
['usergroup', [id => "usr"]]]);

I share Jeff's frustration in the heavily object oriented approach to doing things with traditional .NET libraries - but I think it points to two things: first, the libraries we get sometimes are a clunky "one size fits all" offering that leave the developer writing a lot of line noise for a simple result, and second that while the language itself may not be the initial culprit (I think the two shorter examples above could be duplicated in C#, for example) the thinking one acquires from their language, libraries, and best practices is why System.Xml makes some developers think that 17 lines of code is the best for a "trivial" example of generating some xml.

This is why language is so interesting to me: the way you think is overwhelmingly influenced by how you express yourself.

Where does that discussion leave me? Wanting to know more about Ruby and work on my fluency in Perl. I may have to write that C#, but I want more flexibility in thinking.


No comments: