One of the things that bothers me a lot is using a lot of string concatenation when you can just use the verbatim string literal (@"") to define a large block of text. For example, I saw some code on a blog the other day that looked something like this:
string strValue = "<div id='test'>";
strValue += "<input type='text' id='name' value='" + strName + "/>";
strValue += "<input type='submit' />";
strValue += "</div>";
// Many more lines before it finally
// finished building the string
There are many things wrong with the code sample above including not using StringBuilder. I have seen the same type of code extensively with VB and VBScript mostly due to the lack of a multi-line string and VB and VBScript don't have the concatenation operator either so you end up using strValue = strValue + "stuff".
The issue I have with code like this is both efficiency and maintainability and significant difficulty supporting translations. I once had to maintain a SharePoint 2003 server-side control (not a lot of fun!) that built a lot of html that was sent to the browser. The code was even originally developed by a Microsoft consultant, but it was a mess of string concatenation similar to the first example. I converted the string html to use the verbatim string literal like:
@"<div id='test'>
<input type='text' id='name' value='" + strName + @"/>
<input type='submit' />
</div>";
But even this is hard to pick out the variable assignments in the string. A more generic version is desired, such as:
@"<div id='test'>
<input type='text' id='name' value='${name}' />
<input type='submit' />
</div>";
At this point, it is easy to use Replace or a RegEx to specify the variable values. The downside is potential performance issues with Replace or RegEx, but the upside is less string concatenation and maintainability. It is easy to place the string in a resource or in configuration where it can be maintained outside of code.
Technorati tags:
c#,
strings