[Glass] printString and asString
Otto Behrens
otto at finworks.biz
Fri Jan 3 00:33:21 PST 2014
Hi,
I've run into one of my favorite problems in Smalltalk and decided to
try the list. Please don't shoot me on this one; perhaps you've run
into it yourself. If there are discussions that I should read, please
send me some info.
My first assumption is that the difference between printString and
asString is that printString may be more elaborate than asString, but
often they are the same. Do you agree?
1. In Pharo, the default implementation of asString is ^ self printString.
2. printString normally calls self printOn: aStream. (Pharo and
GemStone. Yay, consistency!)
3. In Pharo, the default printOn: writes the class name prefixed with
'a' or 'an'.
4. In GemStone, the default implementation of printOn: writes self
asString to the stream.
My second assumption is one should never override printString. Rather
override printOn:. Agreed?
In Pharo, we have very few classes that overrides printString. One
problem area is UUID. It overrides asString, printOn: and printString,
with a similar approach to GemStone in printOn:. In GemStone, there's
a big heap of inconsistency. Character also overrides all 3 methods,
with an apparent awful inconsistency there!
In Pharo, I get infinite recursion when I override printOn: to call
asString. I get infinite recursion problems in GemStone when I
override asString and call printString. So with my strategy to develop
in Pharo and deploy in GemStone, we have to be very careful.
Most often, overriding printString and / or asString has to do with
performance. If we have a simple object, we don't want to override
printOn: that creates a stream, prints an instanceVariable (already a
string) to it, and then throw away the stream.
My suggestion is that we should get consistency. Decide on a way and
follow that. To me, this makes sense:
1. Keep the default printString that calls printOn:.
2. Override asString to return a simple representation of the object,
if you have one. Don't create streams in here, or go wild with string
concatenations. Practically, many objects will return a simple string,
which could be one instVar.
3. Override printOn: to return a representation concatenating parts of
the object as strings. Use this if you want to print a more elaborate
description than asString.
4. Change Object >> asString return 'a' or 'an', class name.
5. Change Object >> printOn: to write self asString to the stream.
6. Fix printString overrides (more work in GemStone than Pharo)
7. Normally use printString, but use asString where you are concerned
about performance. In some cases, you may have a longer printString...
Well, thanks for reading this far. Looking forward to your answers.
Otto
More information about the Glass
mailing list