PITADEV
Curiosity killed the developer's project.

Code Aphorisms

Wednesday, 3 December 2008 21:56 by aj

At the risk of unsettling others that have talked about poetic code, have URLs with the post-title I originally wanted to use, or have even gone so far as writing a book on the subject, I'd like to talk about the beauty of code.  Not all code, not just any code, but lines of code that get the job done artistically.  Sometimes it involves thinking in a way that logically short-circuits the kind of spagettastic novellas encouraged by bygone paradigms like VB6.  Other times, it's using language features to accomplish something with unusual elegance.  Sometimes, lines of code are just really neat.

As I said above, lots of people have talked about this before, so to take a stab at semi-originality I've chosen the word "aphorism."  By definition, an aphorism is generally used on a cultural, moral, or ethical level, and applies to verbal language, like a saying or adage.  For example, Jesus was full of aphorisms.  I like this word, and this is my post, so I'm going to selectively use the definition to apply to computer programming, as "a terse [passage of code] embodying a general truth [or principal]," where "truth [or principle]" is an operation, action, or necessity.

When I first started writing .Net code in C#, I would often try to smash several lines of code into one line.  The Visual Studio IDE can get pretty nifty with IntelliSense in C#, and casting or adding another dot after a method call yielded many lines of code like this:

regKey.SetValue("Reg Key Name",
  ((CustomConfigurationSection.CustomElement)loadedConfig.
  CustomElementCollection[cmbElementKeys.SelectedItem.
  ToString()]).CustomElementString);

*This is all one line.  Line breaks added so things look clean and neat.  My OCD overfloweth.

Looking back, that line of code isn't really a bad thing, but there's a lot of crap in it, which makes debugging a hassle.  I've aged as a C# programmer, and I've definitely aged as a debugger.  Lines with a ton of implicit fields, casts, and especially multiple operations make the bridge of my nose hurt.  I still write lines of code like this from time to time, but I certainly don't have the starry-eyed appreciation I had for them when I was a wee lad.

Instead, I've grown really fond of fancy semantics and figuring out how to do stuff ways that I haven't done them before.  Hence, I've been busy trying to find practical application for the host of new language features that are included in .Net 3.0/3.5.  Recently, I switched jobs.  Before leaving my old position, someone on my team asked me to fix the exception handling in a class I wrote a few years ago.  As I barfed my way along (I have trouble looking at my own code from years past), I found a chunk of code that posted to a Java servlet in order to do an image conversion.  I had recently learned that the servlet itself, when it failed, would sometimes return raw HTML describing a Javascript alert.  Since the class runs in a multithreaded application driven by a Windows service, whenever this happened, the error returned from the servlet not only didn't get handled, but the application continued running as if everything was fine.  I set about attempting to fix this.  

As part of the exception handling, I needed to pump the stuff from the alert into the application's logging.  System.Net.WebClient.DownloadData() returns a byte array which, when the error appeared, had to become legible.  I thought I'd cram the byte array into a char array and then toss it all into a StringBuilder.  The old me would have muddled around for a bit trying to find a good way to do this, shrugged, and then written this common snippet:

byte[] responseData = webClient.DownloadData(uri);
char[] charData = new char[responseData.Length]();
for(int i = 0;i < responseData.Length;i++)
   charData[i] = Convert.ToChar(byteData[i]);

Sure, it works fine.  It's just chunky and unwieldy and it seems like there should be a better way.  Since I was upgrading the code from 1.1 anyway (big corporation=slow adaptation), I checked the Array namespace for something cool and found Array.ConvertAll<T1, T2>.  Then I realized I could use an anonymous method with the conversion itself, like this:

char[] chardata = 
   Array.ConvertAll<byte, char>(byteData,
   new Converter<byte, char>(delegate(byte c) 
      { return Convert.ToChar(c); }));

I did a small victory dance when this worked.  But the true aphorism only surfaced when I realized that the anonymous method could be further contracted into a Lambda:

char[] chardata = Array.ConvertAll<byte, char>(byteData, 
   b => Convert.ToChar(b)); 

That, my friends, is some sexy frickin' code.  Thank goodness for the freaks on the C# language team that think of this stuff.  With their help, every now and then I get to feel like Jesus.

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5
Tags:   , ,
Categories:   Aphorisms
Actions:   E-mail | del.icio.us | Permalink | Comments (1) | Comment RSSRSS comment feed

Comments