Poorly handled exceptions might speak volumes about someone's coding abilities, but it's string concatenation that's a sure bet to kill a programs readability (thus maintainability). Everyone knows that they should use StringBuilder's for better performance when concatenating a lot, but to improve maintainability, string.format is king!
On the topic of performance though, you'll be glad to know that there's also an AppendFormat method to the stringbuilder class - so readability and performance aren't exclusive concepts!
Surely, I can't be the only one that has a hard time writing and maintaining code like:
document.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 + (or & in VB.NET) to concatenate something to a string, and there's no reason you should either. To write the above code better, try:
document.SelectSingleNode(string.Format("/graph/data[name='{0}']", name));Personally, even though it's a simple example, I find it a lot better - and as things get more complicated you'll be laughing as you code. But wait, there's more! string.Format uses string formatting - so you have a lot of control over how objects are turned into strings. So you coul do
string.Format("Your score is {0:p}", student.FinalExam.Score); which would format the float score into a percentage.
Understanding .NET String formatting is important because (a) it'll make it so you never ask a question about how to get a date in a certain format, (b) how to get a number in a certain format and (c) it's used all over in .NET. For example, that DataBinder.Eval() method actually accepts a 3rd parameter which is the string formatter to use.
Now, like I said earlier, you can also use AppendFormat of the StringBuilder class
StringBuilder sb = new StringBuilder();
sb.Append("<books>");
foreach(Book book in author.Books)
{
sb.AppendFormat("<book isbn=\"{0}\">{1}</book>", book.Isbn, book.Name);
}
sb.Append("</books>");
A word of caution. String.format IS NOT a substitute for using command parameters. But dang, it is sweet for almost everything else!