Wednesday, June 3, 2009

An elegant solution that was completely unnecessary

Working on a web form that would email someone when it was submitted, one of the methods looked like it could use a little refactoring.
   1: private string BuildMessageBody()
   2: {
   3:     StringBuilder messageBuilder = new StringBuilder();
   4:     messageBuilder.Append("Account Number: ");
   5:     messageBuilder.Append(textAccountNumber.Text);
   6:     messageBuilder.Append("\n");
   7: }
It looks kind of ugly and takes up a fair amount of space, I could do string concatenation,


   1: private string BuildMessageBody()
   2: {
   3:     messageBuilder.Append("Account Number: " + textAccountNumber.Text + "\n"
   4: );
but that can get ugly fast and in my opinion it's hard to maintain. So I came up with a brilliant and elegant solution, I would use an extension method!


   1: public static void AppendLine(this StringBuilder builder, string title, string value)
   2: { 
   3:     builder.Append(title); 
   4:     builder.Append(value); 
   5:     builder.Append("\n");        
   6: }

and now my could would look something like this



   1: private string BuildMessageBody()
   2: {
   3:     StringBuilder messageBuilder = new StringBuilder(); 
   4:     messageBuilder.AppendLine("Account Number: ", textAccountNumber.Text);
   5: }

and just as I was thinking how cool Extender methods are it hit me? I could just use StringBuilder.AppendFormat to do basically the same thing like this



   1: private string BuildMessageBody()
   2: {
   3:     StringBuilder messageBuilder = new StringBuilder();
   4:     messageBuilder.AppendFormat("Account Number: {0}\n", textAccountNumber.Text);  
   5: }

Oh well, but just proves that sometimes a cool new way to handle a problem isn't always the right way, and this was a reminder for me to look at existing functionality before I try to create my own.

No comments: