(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).
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.
Comments 2
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
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