programming and human factors

13 Jul 2006

I Heart Strings

Brad Abrams was a founding member of the .NET common language runtime team way back in 1998. He's also the co-author of many essential books on .NET, including bothvolumes of the .NET Framework Standard Library Annotated Reference. I was at a presentation Brad gave to the Triangle .NET User's Group early in 2005. During the Q&A period, an audience member (and a friend of mine) asked Brad this question:

What's your favorite class in the .NET 1.1 common langauge runtime?

His answer? String.

And that's from a guy who will forget more about the .NET runtime than I will ever know about it. I still have my .NET class library reference poster, autographed by Brad right next to the String class.

I've always felt that string is the most noble of datatypes. Computers run on ones and zeros, sure, but people don't. They use words, sentences, and paragraphs to communicate. People communicate with strings. The meteoric rise of HTTP, HTML, REST, serialization, and other heavily string-oriented, human-readable techniques vindicates -- at least in my mind -- my lifelong preference for the humble string.

Or, you could argue that we now have so much computing power and bandwidth available that passing friendly strings around in lieu of opaque binary data is actually practical. But don't be a killjoy.

Surely, I can't be the only one that has a hard time writing and maintaining code like:

d.SelectSingleNode("/graph/data[name='" + name + "']");

When I do write code like the above, I almost always forget my closing quote or square bracket! And as things get more complicated, it becomes a flat out nightmare.

The solution is to make heavy use of string.Format. You'll never EVER see me use plus to concatenate something to a string, and there's no reason you should either. To write the above code better, try:

d.SelectSingleNode(string.Format("/graph/data[name='{0}']", name));

It's a win-win scenario: you get more power and more protection. For a complete rundown of the zillion possible String.Format specifiers, try these links: