[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: the benefits of immutability




Hello,

On Tue, Aug 19, 2003 at 02:33:14PM -0400, James Y. Knight wrote:
[deletia]
> >Frankly, I don't see how anything follows from your comments. I made a
> >point that it was annoying that String couldn't be subclassed, first
> >you claimed (bizarrely) that this was so that String could be
> >immutable (which of course the final StringBuffer type disproves), and
> >then you claimed, bizarrely, that wanting to subclass things is a bad
> >idea so I shouldn't claim this as a problem. I noted that Java depends
> >on subclassing and now you are weaseling again.
> 
> StringBuffer being final disproves nothing. String is final to ensure 
> it is immutable. I don't know why StringBuffer is final. There are many 
> reasons for something being final. Perhaps security reasons, perhaps 
> Sun just screwed up, perhaps a (lame) quest for efficiency. I don't 
> know, but it certainly doesn't affect the discussion about String.

StringBuffer being final is a performance hack: when its 'toString()'
method is called, it uses a package-private 'String' constructor that
reuses its own internal char buffer. This avoids the creation of a new
char array in the following (extremely common) use-case:

  public final String toString ()
  {
	StringBuffer sbuf = new StringBuffer ('[');

	sbuf.append (foo).append (bar);

	return sbuf.append (']').toString ();
  }

(the Java compiler does this dance behind the scenes when the string
concatenation operator is used, btw).

Now we can see why StringBuffer is final: it *must* ensure that the
buffer it shares with the string object will not be modified anymore, or
the "strings are immutable" constraint would be violated. The safest way
to ensure that is to seal the class.

> James

Cu,
Damien.

-- 
Formal symbolic representation of qualitative entities is doomed to its
rightful place of minor significance in a world where flowers and beautiful
women abound.
		-- Albert Einstein
-- 
http://users.swing.be/diederen/