I came across a piece recently that suggested learning a new programming language through unit tests. Sounds like a good idea -- lots of incremental changes, lots of micro-milestones (did your change compile? did it pass the test? move on!).
So I found myself looking through junit today, and found this heinous method lurking in the samples directory (junit/samples/money/Money.java to be precise):
public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("["+amount()+" "+currency()+"]"); return buffer.toString(); }Um, I'm no Java programmer, but that's a pretty smelly piece of code. The basic operation -- string concatenation -- is obviously a primitive operation here, and shouldn't need a StringBuffer to glom these little bits of string together.
This should work just as easily, and a lot more clearly:
public String toString() { return "["+amount()+" "+currency()+"]"; }Yup. All tests pass. ;-)
Re:motivation?
ziggy on 2004-02-26T19:22:44
That may be the origin of "use string buffers everywhere", but this particular usage ignores the received wisdom and while attempting to follow it. If StringBuffers were better, faster, stronger or safer than string concatenation, then why do all of the work through concatenating strings, and keep the string buffer around as window decoration?I'll be charitable and say that this code smell was left in the samples directory so that it could be fixed by the user through experimentation. Whether it should be replaced with simple string concatenation or multiple calls to buffer.append() is a religious war for another day.