Search code examples
javastringstringbuilderreturn-typestringbuffer

Using StringBuffer and StringBuilder as a method return type in Java


Is it a bad idea to use StringBuilder or StringBuffer as a method's return type in a Java ? I have often returned String as a return type from a Java method but never StringBuilder or StringBuffer even I have done operations using them inside a method.

Could anyone please educate me if it is recommended NOT to use StringBuilder and StringBuffer as method return type ? If not, what are the reasons for it ? One reason could be that these two are mutable. But how does it make any difference since we often use other Derived Type as a method return type which are mutable.

Could someone please explain the demerits (if any) of using StringBuffer and Builder as method return type with a code ,maybe?


Solution

  • StringBuffer is old and was substituted by StringBuilder for speed.

    Returning a StringBuilder could be bad style: sometimes it is better to pass a StringBuilder as parameter. Compare:

    [best] As parameter:

    void dump(StringBuilder sb) {
        sb.append(name);
        for (Foo child : children) {
            child.dump(sb);
        }
    }
    

    [unproblematic, inefficient] Comparison with immutable value aggregated:

    String toString() {
        return name + left.toString() + right.toString();
    }
    

    [ugly] Comparison with returning a mutable value:

    StringBuilder dump() {
        StringBulder sb = new StringBuilder();
        for (Foo child : children) {
            sb.append(child.dump()); // Inefficient
        }
        return sb;
    }