Smalltalk Lecture 2
1
Review — Objects in Smalltalk
> Everything is an object
— Things only happen by message passing — Variables are dynamically bound
> Each object is an instance of one class
— A class defines the structure and the behavior of its instances. — Single inheritance
— A class is an instance of a metaclass
> Methods are public
— private methods by convention in “private” protocol
> Objects have private state
— Encapsulation boundary is the object
2
Object
> Objectistherootoftheinheritancetree(well,almost) — Defines the common and minimal behavior for all the objects in
the system.
— Comparison of objects:
– ==, ~~, =, ~=, isNil, notNil
— Printing
– printString, printOn: aStream, print, printNl
– display, displayNl
– Transcript show:, display:, tab, cr
3
Identity vs. Equality
> == tests Object identity
— Should never be overridden
> = tests Object value
— Should normally be overridden
– Default implementation is == ! — You should override hash too!
true false
‘foo’,’bar’ = ‘foobar’
‘foo’,’bar’ == ‘foobar’
4
Printing
> Override printOn: to give your objects a sensible textual representation
Fraction>>printOn: aStream aStream nextPut: $(. numerator printOn: aStream. aStream nextPut: $/. denominator printOn: aStream. aStream nextPut: $).
5
Object methods to support the programmer
error: aString
Signal an error
doesNotUnderstand: aMessage
Handle unimplemented message
halt, halt: aString,
haltIf: condition
Invoke the debugger
subclassResponsibility
The sending method is abstract
shouldNotImplement
Disable an inherited method
deprecated: anExplanationString
Warn that the sending method is deprecated.
6
Numbers
LargeInteger
LargePositiveInteger
7
Abstract methods in Smalltalk
Number>>+ aNumber
“Answer the sum of the receiver and aNumber.”
self subclassResponsibility
8
Abstract methods (part 2)
Object>>subclassResponsibility
“This message sets up a framework for the behavior of the class’ subclasses. Announce that the subclass should have implemented this message.”
self error: ‘My subclass should have overridden ‘, thisContext sender selector printString
9
Automatic coercion
Try various mixed expressions to see how coercion works.
3.3
SmallInteger
SmallInteger
LargePositiveInteger
1000 (5/3)
1 + 2.3
1 class
1 class maxVal class
(1 class maxVal + 1) class
(1/3) + (2/3)
1000 factorial / 999 factorial
2/3 + 1
10
Try this in Java!
1000 factorial
402387260077093773543702433923003985719374864210714632543799910429938512398629020592044208486969404 800479988610197196058631666872994808558901323829669944590997424504087073759918823627727188732519779 505950995276120874975462497043601418278094646496291056393887437886487337119181045825783647849977012 476632889835955735432513185323958463075557409114262417474349347553428646576611667797396668820291207 379143853719588249808126867838374559731746136085379534524221586593201928090878297308431392844403281 231558611036976801357304216168747609675871348312025478589320767169132448426236131412508780208000261 683151027341827977704784635868170164365024153691398281264810213092761244896359928705114964975419909 342221566832572080821333186116811553615836546984046708975602900950537616475847728421889679646244945 160765353408198901385442487984959953319101723355556602139450399736280750137837615307127761926849034 352625200015888535147331611702103968175921510907788019393178114194545257223865541461062892187960223 838971476088506276862967146674697562911234082439208160153780889893964518263243671616762179168909779 911903754031274622289988005195444414282012187361745992642956581746628302955570299024324153181617210 465832036786906117260158783520751516284225540265170483304226143974286933061690897968482590125458327 168226458066526769958652682272807075781391858178889652208164348344825993266043367660176999612831860 788386150279465955131156552036093988180612138558600301435694527224206344631797460594682573103790084 024432438465657245014402821885252470935190620929023136493273497565513958720559654228749774011413346 962715422845862377387538230483865688976461927383814900140767310446640259899490222221765904339901886 018566526485061799702356193897017860040811889729918311021171229845901641921068884387121855646124960 798722908519296819372388642614839657382291123125024186649353143970137428531926649875337218940694281 434118520158014123344828015051399694290153483077644569099073152433278288269864602789864321139083506 217095002597389863554277196742822248757586765752344220207573630569498825087968928162753848863396909 959826280956121450994871701244516461260379029309120889086942028510640182154399457156805941872748998 094254742173582401063677404595741785160829230135358081840096996372524230560855903700624271243416909 004153690105933983835777939410970027753472000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
11
Characters
> Characters:
$a $B $$ $_ $1
> Unprintable characters:
Character space, Character tab, Character cr
12
Strings
ByteArray
13
Strings
#mac asString
12 printString
String with: $A
‘can”t’ at: 4
‘hello’, ‘ ‘, ‘world’
> To introduce a single quote inside a string, just double it.
14
‘mac’
’12’
‘A’
$’
‘hello world’
Comments and Tips
> A comment can span several lines. “TestRunner open”
“This is a longer
comment that spans
multiple lines”
15
Literal Arrays
#(‘hello’ #(1 2 3))
#(#a #b #c)
#(‘hello’ #(1 2 3))
#(a b c)
16
Arrays and Literal Arrays
> Literal Arrays and Arrays only differ in creation time — Literal arrays are known at compile time, Arrays at run-time.
> A literal array with two symbols (not an instance of Set)
#(Set new)
> An array with one element, an instance of Set Array with: (Set new)
an Array(a Set())
#(#Set #new)
17
Dynamic arrays with { }
> { … }is a shortcut forArray new …
Syntax error
#(7 12)
#(7 12)
#(5 + 2 . 3 * 4 )
{ 5+ 2. 3 *4 }
Array with: 5+2 with: 3*4
18
Symbols vs. Strings
> Symbols are used as method selectors and unique keys for dictionaries
— Symbols are read-only objects, strings are mutable
— A symbol is unique, strings are not
!
NB: Comparing strings is slower than comparing symbols by a factor of 5 to 10. However, converting a string to a symbol is more than 100 times more expensive.
true
true
true
false
true
true
true
false
‘calvin’
true
‘calvin’ = ‘calvin’
‘calvin’ == ‘calvin’
‘cal’,’vin’ = ‘calvin’
‘cal’,’vin’ == ‘calvin’
#calvin = #calvin
#calvin == #calvin
#cal,#vin = #calvin
#cal,#vin == #calvin
#cal,#vin
(#cal,#vin) asSymbol == #calvin
19
Variables
>
A variable maintains a reference to an object — Dynamically typed
— Can reference different types of objects
— Shared (initial uppercase) or local (initial lowercase)
variable
Shared variable
private variable
Class variable
Global variable Pool variable
instance variable
temporary variable
method parameter : block parameter
| method temporary | | block temporary |
named
indexed
20
Assignment
> Assignment binds a name to an object reference
— Not done by message passing!
— Method arguments cannot be assigned to!
– Use a temporary instead
— Different names can point to the same object!
– Watch out for unintended side effects
|p1 p2|
p1 := 3@4.
p2 := p1.
p1 setX: 5 setY: 6.
p2
5@6
21
Global Variables
> Always Capitalized (convention)
— Stored in the Smalltalk System Dictionary
> Avoid them!
22
Global Variables
> To remove a global variable:
Smalltalk removeKey: #MyGlobal
> Some predefined global variables:
Smalltalk
Classes & Globals
Undeclared
A PoolDictionary of undeclared variables accessible from the compiler
Transcript
System transcript
ScheduledControllers
Window controllers
Processor
A ProcessScheduler list of all processes
23
Instance Variables
> Private to an object
— Visible to instance methods of the defining class and subclasses
— Has the same lifetime as the object
— Define accessors (getters and setters) to facilitate initialization
– Put accessors in a private category!
24
Six Pseudo-Variables
> The following pseudo-variables are hard-wired into the Smalltalk interpreter.
nil
A reference to the UndefinedObject
true
Singleton instance of the class True
false
Singleton instance of the class False
self
Reference to this object
Method lookup starts from object’s class
super
Reference to this object (!)
Method lookup starts from the superclass
thisContext
Reification of execution context
You won’t need to understand this variable
25
Pair class (GNU Smalltalk syntax)
Object subclass: #Pair.
Pair instanceVariableNames: ‘x y’.
Pair extend [ getX [ ^x ] getY [ ^y ]
setX: a [ x := a ]
setY: b [ y := b ] ].
26
Alternative GNU Smalltalk syntax
Object subclass: Pair [ |x y|
getX [ ^x ]
getY [ ^y ] setX: a [ x := a ] setY: b [ y := b ]
].
27
Pair client
p := Pair new. p getX printNl. p getY printNl. p setX: 100.
p setY: ‘hello’. p getX printNl. p getY printNl.
nil
nil 100 ‘hello’
28
Triple subclass and client
Pair subclass: Triple [ |z|
getZ [ ^z ]
setZ: c [ z := c ] ].
t := Triple new setX: 3.14159; setY: $C; setZ: true. t getX printNl.
t getY printNl.
t getZ printNl.
3.14159 $C
true
29
Meta-programming
current := Triple.
[current notNil] whileTrue:
[Transcript display: current; tab;
display: current selectors size; cr.
current := current superclass]
Triple 2
Pair 4
Object 127
30
Recap
Object subclass: #Pair. p := Pair new.
…
Pair subclass: #Triple. t := Triple new.
…
> Subsequent diagrams contain two types of links: — Ifxisasubclassofy,andyisthesuperclassofx
xy
— Ifxisaninstanceofy,andyistheownerclassofx
xy
31
Most programmers should visualize the situation this way
Class Object Pair Triple
pt
32
But here is a more accurate representation
Metaclass of Class
Metaclass of Object
Metaclass of Pair
Metaclass of Triple
Class Object Pair Triple
pt
33