Posts Tagged ‘StringBuilder’

Vim indoctrination

Thursday, April 9th, 2009

Having used Vim (mostly gVim) exclusively for the last year or so my muscle-memory has thoroughly set. Which I was reminded of yesterday when a classmate from Uni asked me if I could lighten his load a bit by quickly adding a piece of functionality to some code he was working on.

“Sure” I thought, I can do this. So I launched Eclipse to carry out a small scale controlled environment kind of test. The task was to, from an existing for-loop with its own functionality, add in the required statements to have the loop also build a comma-separated string of the values retrieved by the loop.

That little adventure madeĀ  me discover of two things:

  1. “:w” won’t save the file in Eclipse… it will however insert those very characters into the code, breaking it. The same goes for “V”, “d” and “Y”. Also, “,cc” won’t comment out a line… that readjustment from Vim to Eclipse took way more time than hacking the actual Java
  2. Python has spoiled me

But all in all, it worked out pretty good, and I got to use StringBuilder for the first time ever. The resulting code looked something like this:

StringBuilder sb = new StringBuilder();
for-loop here {
    pre-existing code here...
    if (sb.length() > 0) {
        sb.append(",");
    }
    sb.append(obj.toString());
}
String s = sb.toString();

I’m sure there are better ways to accomplish this, like just tacking on a comma after each append and then on the resulting string working some string-manipulation magic to remove the final trailing comma, but for some inexplicable reason this just “felt” like a better solution.

It might just be that now most of the actual code is grouped together, so in the event of a refactoring, there is less of a risk that the string manipulation code is forgotten.

Anyway, it was almost fun to hack Java again… almost… ;)