The differences between StringBuilder
and StringBuffer
in Java are well documented and have been touched upon in StackOverflow as well.
Basically, StringBuilder
is a non-synchronized copy of StringBuffer
, with pretty much the same interface since it was intended as a faster drop-in replacement for StringBuffer
. Their API is practically identical and they are actually subclasses of the same inaccessible abstract class in the current JDK.
The one thing I wonder about, therefore, is why they are not publicly related. Having both classes implement a common interface or even having StringBuffer
as a subclass of StringBuilder
would make sense, allowing the existence of shared code for both classes.
So why this forced separation? Was it so that programmers would not inadvertently mix thread-safe with thread-unsafe code? Or was it just a design oversight that will now be inherited to the end of eternity?
EDIT:
To make things clear: I can speculate on why things are like this, but I am hoping for concrete references to an actual decision, e.g. during a JSR process. Anything that would shed some light on what, to me, is a situation that causes a certain amount of difficulty occasionally.
EDIT 2:
The fact that both classes implement Appendable
completely slipped my mind. Probably because that particular interface is useless for most purposes - it can only append a single character or a prepared object and that's it. In most cases it's no more useful than both classes being subclasses of Object
.
EDIT 3:
Well, here is the rationale for exactly this question from a semi-official source:
Evaluation by the libraries team:
It is by design that StringBuffer and StringBuilder share no common public supertype. They are not intended to be alternatives: one is a mistake (StringBuffer), and the other (StringBuilder) is its replacement.
Clearly the lack of a common supertype can, in some cases, slow the hoped-for migration from StringBuffer to StringBuilder. The flip side is that by adding a common supertype, we'd be taking the errors of our past and enshrining them in a public interface to be with us for all time. This doesn't merely slow the migration: it derails it.