StringBuilder: Enabling Bad Algorithms Since .NET 1.0

Oct 11, 2010 17:47


(Yes, I know Java had it first, but I'm in a .NET environment here.)

It's been years since I posted a coding tip/rant. Time for a new one.
Minor rant of interest only to coding geeks under here... )

internet development, work

Leave a comment

Comments 2

enkorvaks October 11 2010, 08:30:23 UTC
(This is Java, but the principle is much the same)

As far as I can tell, the "correct" way to use StringBuilder/StringBuffer is:

public String toString() {
StringBuffer result = new StringBuffer();
result.append("First bit");
result.append(variable);
result.append(otherVariable);
/* repeat as needed */
return new String(result);
}

and not, as some (I hope) autogenerated code would have it:

public String toString() {
StringBuffer result = new StringBuffer();
result = result.append("First bit")
.append(variable);
result = result.append(otherVariable);
/* repeat as needed */
return new String(result);
}

However, doing this in the way your anti-pattern suggests is appalling. Also, if any of your items have a comma in them, automated parsing the output becomes very difficult, indeed. I know, I have just spent the better part of three weeks updating a parser that someone else had written (in python).

Reply

travisjhall October 11 2010, 13:24:06 UTC

The latter will work just fine in .NET, as StringBuilder's .Append method is written with chaining in mind. Assigning the return value back into the variable is unnecessary, but that's a fairly minor inefficiency, and the chaining can help to make it obvious which bits should go together.

But otherwise, yes, that'd be the intended use of StringBuilder. It's just the way this is combined with business logic to work out what the resultant string should be is usually hideous.

Parsing the output isn't usually an issue, because this sort of thing is usually done for display to a human.

Reply


Leave a comment

Up