tags:

views:

162

answers:

3

This is a question out of curiousity. Today I took a look at the implementations of StringBuilder and StringBuffer. Here's the append() method:

public StringBuilder append(String str) {
    super.append(str);
    return this;
}

AbstractStringBuilder.append(str) also returns this. Are there any benefits of discarding the return value (in StringBuilder.append(..)) and returning this again, instead of casting the return value of the super call to the current concrete implementation.

+7  A: 

My first thought is that casting can be expensive, so if it can be avoided that would be best.

Adam Batkin
It's not expensive compared to most other things, but if it can be (easily) avoided in a *very* frequently called API method then that's clearly a good thing.
Michael Borgwardt
+2  A: 

I'm not sure it has to do with the cost of casting.

My opinion is that the method has been written like this in case future needs require to do more than what's done in the super class.

public StringBuilder append(String str) {
    super.append(str);

    // do something more?

    return this;
}

Or the method definition has been auto-generated by the IDE at the time the class was written. Or it's just a matter of coding style.

Gregory Pakosz
+2  A: 

Because

public StringBuilder append(String str) {
    return (StringBuilder) super.append(str);
}

is quite ugly. It isn't even shorter.

(There are languages that support this directly. Something like:

abstract class AbstractStringBuilder{
  type T = this.type
  def append(str : String) : T = ...
}

abstract class StringBuilder{
  //already defined by AbstractStringBuilder return type is StringBuilder
}

)

Thomas Jung
The alternative is also slower as a cast is performed.
Peter Lawrey