Changing strings

jennyw jennyw at dangerousideas.com
Tue Apr 23 04:56:52 UTC 2002


On Mon, Apr 22, 2002 at 11:35:23AM -0700, C. Gable Watts wrote: 

> When a method or expression is compiled, if the same string literal appears
multiple times in the method the SAME String object is reused for the literal
in the method (for space efficiency).  But the compilation of a DIFFERENT
method (or expression) will use a different String object.

Yes, I realized this after I posted. I thought I had experimented with an init method that 
initialized an instance variable to 'squeak' but realized later that while I did make this test 
class I didn't actually try it.  Oops! So now it doesn't seem quite so bad.

> - In some Smalltalk's separate String objects are made for each string
literal in a method.
> - In some Smalltalk's (like Squeak at the moment) equal string literals in
the same method share the same String object.
> - In some Smalltalk's, a string literal in a method is compiled as an
immutable (StringLiteral) object (which cannot be changed with at:put: for
example).
> 
> This latter way is the way it really should work. It should not be possible to modify string literals.  So that attempting to execute the expression
> 	'squeak' at: 6 put: $l.
> would give a 'Message not understood: at:put:' generated by the LiteralString object, 'squeak', because it does not understand the message at:put: (because its an immutable (unchangeable) object).
> 
> But, instead, it is just considered inappropriate (bad programming practice) to modify a String literal and it is considered risky to modify a String that was passed to you that might be a string literal.  A case of a common practise arising over the decades to avoid a problem that should have been fixed "lower down".  It should be impossible to do it (modify a string literal) but instead we all just try to avoid doing it.  :-)

Yes, I agree that making it immutable would be the best. I'm mostly thinking of 
this from the perspective of teaching Squeak to someone else (in particular to 
7th and 8th graders).  I ran across this when I was following an example in 
Chammond Liu's "Smalltalk, Objects, and Design" ... I noticed that Squeak 
didn't behave the way he described a couple Smalltalk dialects as behaving.

Jen



More information about the Squeak-dev mailing list