Change the way an Object is printed: Difference between revisions

From Cuis CookBook
Jump to navigation Jump to search
(imported material)
 
(imported material)
Line 3: Line 3:
'''Solution'''. In the User object define the method <code>printOn:</code>. Watch how it is defined on the class <code>Object</code> and change it a bit, for example as:
'''Solution'''. In the User object define the method <code>printOn:</code>. Watch how it is defined on the class <code>Object</code> and change it a bit, for example as:
printOn: aStream
printOn: aStream
|str|
|str|
str _ ((self class name withArticle) , '-', self id asString).
str := ((self class name withArticle) , '-', self id asString).
aStream nextPutAll: str.
aStream nextPutAll: str.
Cy. Defect: The method above is a bit Pythonic.
Cy. Defect: The method above is a bit Pythonic.


This method definition is more Smalltalkish:
This method definition is more Smalltalkish:
printOn: aStream
printOn: aStream
aStream
aStream
nextPutAll: self class name;
nextPutAll: self class name;
nextPut: $-;
nextPut: $-;
nextPutAll: self id asString
nextPutAll: self id asString
Voila, now if you print a user you will see something like <code>aUser-2132</code>. This very practical when you are listing several user objects, for the example in the inspector.
Voila, now if you print a user you will see something like <code>aUser-2132</code>. This very practical when you are listing several user objects, for the example in the inspector.
----NM 10-Aug-2021. Tested Cuis5.0-4738.image
----NM 10-Aug-2021. Tested Cuis5.0-4738.image

Revision as of 23:24, 3 May 2025

Problem. Suppose you defined a Class, say User, and suppose this class contains the instance variables name, id, password. When you create a new User object, it will print itself as aUser. This might be ok, but suppose it is usefull for you to always see id. What to do?

Solution. In the User object define the method printOn:. Watch how it is defined on the class Object and change it a bit, for example as:

printOn: aStream
 |str|
  str := ((self class name withArticle) , '-', self id asString).
  aStream nextPutAll: str.

Cy. Defect: The method above is a bit Pythonic.

This method definition is more Smalltalkish:

printOn: aStream
   aStream 
      nextPutAll: self class name;
      nextPut: $-;
      nextPutAll: self id asString

Voila, now if you print a user you will see something like aUser-2132. This very practical when you are listing several user objects, for the example in the inspector.


NM 10-Aug-2021. Tested Cuis5.0-4738.image