Wrong way to use StringBuffer.toString()

22 Sep 2005

Andriy Rozeluk found another case for PMD to catch; the RFE is here. Here's a code sample:

class Foo {
  void bar(StringBuffer sb) {
    // Should just use sb.length() == 0
    if (!sb.toString().equals('')) {   
      sb.append(',');
    }
  }
}

This is bad because StringBuffer.toString() creates a new String object which gets thrown away immediately after the equals('') check. Blah!

What other wasteful method chaining idioms are out there that PMD could catch?