2. Contents
‣ Introduction
‣ Origins of Smalltalk
‣ Key Concepts
‣ The Smalltalk Object Model
‣ Messages
‣ Metaclasses & Reflection
‣ Conclusion
Michele Lanza 2 Smalltalk in a Nutshell
3. Sources
‣ Own Material from the PF2
course
‣ Own Material from the Smalltalk
course given in Bern
‣ External Material by
‣ Stéphane Ducasse, INRIA Lille
‣ Oscar Nierstrasz, Univ. of Bern
‣ “Squeak by Example” by Andrew
Black, Stéphane Ducasse,
Oscar Nierstrasz, Damien Pollet
Michele Lanza 3 Smalltalk in a Nutshell
5. What is Smalltalk?
‣ A pure object-oriented programming language
‣ “everything is an object”
‣ single inheritance, dynamically typed, truly reflective
‣ The origin of many innovations in OO development
‣ RDD, IDEs, MVC, XUnit, Refactorings, Design Patterns,...
‣ An improvement over many of its.. successors!
‣ An integrated development environment
‣ Class browser, debugger, inspector, refactoring engine, etc.
‣ A philosophy of development
‣ A “living universe” driven by a virtual machine
Michele Lanza 5 Smalltalk in a Nutshell
6. Smalltalk: a State of Mind!
‣ Small and uniform language
‣ Syntax fits on one sheet of paper
‣ Large library of reusable classes
‣ Advanced development tools
‣ Interactive virtual machine technology
‣ Truly platform-independent
‣ Team-working Environment
‣ Releasing, versioning, deploying
Michele Lanza 6 Smalltalk in a Nutshell
7. Smalltalk vs. C++ vs. Java
Death Match Smalltalk C++ Java
Object model Pure Hybrid Hybrid
Garbage collection Automatic Manual Automatic
Inheritance Single Multiple Single + Interfaces
Type System Dynamic Static Static
Reflection Fully reflective Introspection Introspection
Concurrency Semaphores, Monitors Some libraries.. Monitors
Categories, namespaces,
Modules bundles, packages, ...
Namespaces Packages
Michele Lanza 7 Smalltalk in a Nutshell
8. Smalltalk Implementations
Platform Details
Unix, Linux, based on Xerox PARC specs, but highly optimized.
Visualworks Windows, Mac Binary cross-platform
Windows,
ObjectStudio Mainframes
similar to VisualWorks, one day they will merge
everything, free and open, based on the ST-80 specs.
Squeak everything Effort started by Kay with a focus on Multimedia
Unix, Linux,
Gemstone/S Windows
server-side, persistent, multi-user, active ODBMS
native widgets, tight integration with Windows.
Dolphin Windows
Was free, became commercial, now free again
Unix, Linux,
Smalltalk X Windows
splendid implementation of the ANSI standard
Unix, Linux, free, well-versed for scripting
GNU Smalltalk Windows maintained by our very own Paolo Bonzini :-)
Unix, Windows,
VisualAge OS/2
cross-platform via source, percursor to Eclipse
Michele Lanza 8 Smalltalk in a Nutshell
9. Community
‣ European Smalltalk User Group
‣ esug.org
‣ Squeakworld
‣ squeak.org
‣ Smalltalk Industry Council
‣ stic.org
Michele Lanza 9 Smalltalk in a Nutshell
10. Recommended Books
‣ Andrew Black, Stéphane
Ducasse, Oscar Nierstrasz,
Damien Pollet, “Squeak by
Example”, 2007
‣ Alec Sharp, “Smalltalk by
Example”, MacGraw-Hill, 1997
‣ Kent Beck, “Smalltalk - Best
Practice Patterns”, Prentice Hall,
1997
‣ Sherman Alpert et al., “The
Design Patterns Smalltalk
Companion”, Addison-Wesley,
1998
Michele Lanza 10 Smalltalk in a Nutshell
12. The Roots
‣ Conceived in the late 60’s by Alan Kay, inspired by
‣ Douglas Engelbart - NLS (the oNLineSystem) to augment the
human intellect, 1966
‣ Seymour Papert - The Logo programming language, 1968
‣ Ivan Sutherland - Sketchpad, 1963
‣ LISP (Interpreter, Garbage Collection, Blocks)
‣ Simula (Classes, Message sending)
‣ Kay’s background in biology: the concept of communicating
“cells” which later became “objects”
Michele Lanza 12 Smalltalk in a Nutshell
13. Xerox PARC
‣ The “Palo Alto Research Center” of
Xerox
‣ Kay moved to PARC in 1972 to lead
the “Learning Research Group” and
work on Smalltalk, a language for
teaching programming to children
‣ PARC, incubator of many concepts of
modern computing, such as Graphical
User Interfaces, Interpress (the
precursor of Postscript), the Ethernet,
the Laser printer (!), WYSIWYG
editors, etc.
Michele Lanza 13 Smalltalk in a Nutshell
14. The Dynabook & The Alto
‣ The Dynabook, Kay’s vision
of a laptop for children
‣ The Alto, a machine to run
Smalltalk
‣ Precursor to Apple’s Lisa
http://www.artmuseum.net/w2vr/archives/Kay/01_Dynabook.html
Michele Lanza 14 Smalltalk in a Nutshell
15. The Good Old Days...
Michele Lanza 15 Smalltalk in a Nutshell
16. Precursor, Innovator, Visionary
‣ 1st based on graphics (new hardware needed!)
‣ Multi-window environment (overlapping windows)
‣ IDE with debugger, compiler, text editor, etc.
‣ Browsing with a “pointing device” (yes...a mouse)
‣ Virtual machine
‣ Garbage collection
‣ Just in time compilation
‣ Everything is there, the complete source code
‣ Ideas were taken over by Apple and Microsoft
Michele Lanza 16 Smalltalk in a Nutshell
18. This is weird...
“Try not to care - Beginning Smalltalk programmers
often have trouble because they think they need to
understand all the details of how a thing works before
they can use it.
This means it takes quite a while before they can
master Transcript show: ‘Hello World’.
One of the great leaps in OO is to be able to answer
the question quot;How does this work?quot; with quot;I don’t carequot;“.
Alan Knight, Smalltalk Guru
Michele Lanza 18 Smalltalk in a Nutshell
19. The Smalltalk “Image”
‣ Smalltalk uses image files, containing everything
‣ the complete source code of the language and more than 1000
library classes & the compiled byte-code
‣ The VM “executes” the image, where everything is alive,
i.e., an object: Talk to whatever you want!
Smalltalk Java
Edit- and Run-time Edit-time Run-time
Independence
Hardware
The image
Source-code Byte-code
(*.java) (*.class or *.jar)
Source-code Byte-code
Dependence
Hardware
Smalltalk Virtual Machine Java Virtual Machine (JVM)
Computer Hardware
Michele Lanza 19 Smalltalk in a Nutshell
20. Syntax on a post card
tax
example WithNumber: x of Smal ltalk method syn
tr ates every part sages,
“A m ethod that illus binary, and key word mes
t primitives . It has unary, block temporarie
s),
excep (but not
and temporaries ), uses
de clares arguments not an i nstance variable
ses a globa l variable (but , integer, float
), uses
acces string
h aracter, symbol, d has
li terals (array, c nil, sel f, and super, an
ble true false, zero
the pseudo varia and casc ade. It has both
sequence , ass ignment, return oesn’t do anything usef
ul,
argum ent blocks. It d
argument and one
though.”
t].
|y| Nil) if False: [self hal
true & fal se not & (nil is
size.
y := se lf size + super
ach |
#($a #a ‘a ’ 1 1.0) do: [:e
name);
Transcript sh ow: (each class
g);
show: (each printStrin
show: ‘ ‘].
^ x < y
Michele Lanza 20 Smalltalk in a Nutshell
21. Smalltalk syntax in a nutshell
Element explained exemplified
^ return ^’hello world’
‘ string a string’
“ comment “smalltalk stinks”
. separator self foo. self bar
; cascade self foo; bar
# literal objects #mac #(1 2 3)
[] block [: var | | tmp | expr ]
|| local or block variable | temp |
:= assignment foo := 27
$ character $b $a $r
: end of selector name do:with:
Michele Lanza 21 Smalltalk in a Nutshell
22. Hello World!
‣ Transcript show: ‘Hello World!’
‣ This is a message
‣ The object (actually it’s a class ;-) Transcript is the receiver of
the message
‣ The selector of the message is #show:
‣ The argument is the string ‘Hello World!’
‣ Vocabulary concerns: Message passing or sending is
equivalent to “invoking a method” in Java or C++
Michele Lanza 22 Smalltalk in a Nutshell
23. Smalltalk is weird
‣ It looks like an interpreted language
‣ but in reality it’s compiled just in time
‣ You can interact with all objects within the image
‣ DoIt; execute the currently selected code
‣ PrintIt; do & print the currently selected code
‣ InspectIt; do & inspect the currently selected code
‣ AcceptIt; in the context of methods and classes: compile!
‣ These are not messages, only an idiom for interaction!
Michele Lanza 23 Smalltalk in a Nutshell
24. Defining Classes & Variables
‣ Edit the class creation template
class name
superclass name
instance variables
Michele Lanza 24 Smalltalk in a Nutshell
25. Defining Methods: Fill in the template
‣ Smalltalk methods always return the object they belong
to, unless specified otherwise
Michele Lanza 25 Smalltalk in a Nutshell
26. Let’s see this Smalltalk thingy!
Michele Lanza 26 Smalltalk in a Nutshell
27. The Smalltalk Type System
‣ Smalltalk is a dynamically typed
language
‣ You don’t care about the types of
your variables, as long as they
can respond to the message you
send them
‣ Ruby programmers call this “duck
typing”
‣ There are some fancy things like
#become: but it’s out of scope
Michele Lanza 27 Smalltalk in a Nutshell
28. Blocks and Control Constructs
‣ All Smalltalk control constructs are implemented by
message passing
‣ No keywords; open & extensible
‣ A block is a closure (== a lambda abstraction)
‣ A function that captures variable names in its lexical context
‣ A first-class value that can be stored, passed, evaluated
‣ Useful to delay evaluation
[ :arg1 :arg2 | | temp1 temp2 | expression. expression ]
|sqr|
sqr := [ :n | n*n].
sqr value: 5
[:x :y | x + y + 3 ] value: 3 value: 4
Michele Lanza 28 Smalltalk in a Nutshell
29. Booleans
‣ Slick implementation
‣ true and false are unique Object
instances of True and False ...
...
‣ Lazy evaluation with and: and Boolean
or: ifTrue:IfFalse:
not
&
false and: [ 1 / 0 ]
10 odd ifTrue: [ .. ] ifFalse: [ .. ]
True False
‣ Blocks and Booleans are Crucial
ifTrue:IfFalse: ifTrue:IfFalse:
not not
& &
for the implementation of loops
Michele Lanza 29 Smalltalk in a Nutshell
30. Looping Madness
‣ Various kinds of loops are possible
| n |
n := 10.
[ n > 0 ] whileTrue:
[ Transcript show: n printString; cr. n := n - 1 ]
1 to: 10 do: [ :n | Transcript show: n printString; cr ]
10 timesRepeat: [ Transcript show: ‘hi’; cr ].
‣ But loops without Collections are just half as fun..
Michele Lanza 30 Smalltalk in a Nutshell
31. Collections
‣ The Collection hierarchy offers many of the most powerful
classes in the Smalltalk system
‣ It would be enough material for a lecture itself!
‣ Some of these classes have been around for more than 30
years! Therefore: Do not program your own collections...
Object
Collection
SequenceableCollection Set Bag
ArrayedCollection OrderedCollection LinkedList Dictionary
Array String Text SortedCollection Interval IdentityDictionary
ByteString Symbol Heap
Michele Lanza 31 Smalltalk in a Nutshell
35. The Smalltalk Object Model
‣ Simple & uniform
‣ everything is an object
‣ objects communicate by sending each other messages
‣ The rules of the model
1. Everything is an object
2. Every object is an instance of a class
3. Every class has a superclass
4. Everything happens by message sends
5. Method lookup follows the inheritance chain
Michele Lanza 35 Smalltalk in a Nutshell
36. Everything is an object
‣ The Smalltalk mantra: Smalltalk is a consistent, uniform
world written in itself
‣ The whole language is there and can be easily modified
‣ Everything is an object!
‣ The workspace, the window, the scroll bar, 1, 3+4, 100 factorial,
‘hello world’, the mouse, the parser, the compiler, the process
scheduler, etc. etc.
‣ Classes are objects too!
‣ What? Yes, they are even first-class objects...you can send them messages,
inspect them, etc.
‣ Smalltalk is a truly reflective system!
Michele Lanza 36 Smalltalk in a Nutshell
37. Every object is an instance of a class
‣ A class defines the structure of its instances via instance
variables and the behavior of its instances via instance
methods
‣ Each method has a name, called its selector, which is unique
within the class
‣ Every object has a class, find out by sending the
message #class to it
1 class -> SmallInteger
20 factorial class -> LargePositiveInteger
‘hello’ class -> ByteString
#(1 2 3) class -> Array
(4@5) class -> Point
Object new class -> Object
Michele Lanza 37 Smalltalk in a Nutshell
38. Instance Variables
‣ Instance variables are “private” to the instance..
‣ Java or C++ allow instance variables (called “members” or
“fields”) to be accessed by any other instance of the same
class
‣ The encapsulation boundary of objects in Java/C++ is the class, in
Smalltalk it is the instance
‣ ..and “protected” to the subclasses
‣ Otherwise it is impossible to access them, unless one defines
accessor methods
Michele Lanza 38 Smalltalk in a Nutshell
39. Instance Methods
‣ All methods are “public”
‣ Methods are grouped into protocols the indicate their
intent
‣ They are conventions, not constraints..
‣ Methods can access all instances variables of the object
‣ Some Smalltalkers prefer to do so only through accessors
‣ While this does not imply a performance penalty, it’s a questionable
practice because you expose the state..
Michele Lanza 39 Smalltalk in a Nutshell
40. Wait a second...
‣ If classes are objects too and every object is an instance
of a class...
‣ Yes, classes are also instances of classes
‣ They are instances of metaclasses
‣ A metaclass is a class whose instance is a class
‣ It defines the structure and behavior of its instance, the class
‣ In 95% of the cases the metaclass is empty
‣ Whenever you create a class, the system automatically
creates the corresponding metaclass
Michele Lanza 40 Smalltalk in a Nutshell
41. The Instance Side and The Class Side
‣ Classes are objects, therefore they have their own (class)
instance variables and (class) methods
‣ A class and its metaclass are separate but tightly related
‣ The browser enforces this separation through the GUI
‣ Class methods & variables are similar to “static” members
in primitive languages
Michele Lanza 41 Smalltalk in a Nutshell
42. Every class has one superclass
‣ Single inheritance
‣ The root of the world is Object
‣ Abstract classes and methods
‣ No syntactic construct to indicate abstractness
‣ Convention: A method is abstract it its body is “self
subclassResponsibility”
‣ A class is abstract if it contains an abstract method
Michele Lanza 42 Smalltalk in a Nutshell
43. Everything happens by message sends
‣ The essence of Smalltalk: you do not care who
implements things
‣ You politely ask objects to perform things for you
‣ ...who in turn may ask other objects for doing those things
‣ This leads to short methods and lots of message sends
‣ “Don’t do anything that you can push off onto someone else”
‣ Everything is dynamic, even messages to classes who in
turn are just objects!
Michele Lanza 43 Smalltalk in a Nutshell
44. Nearly everything happens by message sends
‣ At some point action must take place
‣ Variable declarations
‣ Variable assignments
‣ Returns
‣ Primitives
‣ Pretty much everything else truly happens by message
sends
‣ In particular accessing fields: since there are only private
fields, you must provide accessor methods
Michele Lanza 44 Smalltalk in a Nutshell
45. Method lookup follows the inheritance chain
‣ What happens when an object receives a message?
‣ The class of the receiver looks up the method to use to handle
the message
‣ If the class does not have that method, it asks its superclass, and so
on, up the inheritance chain
‣ When the method is found, the arguments are bound to the
parameters of the method, and the VM executes it
‣ What if a method does not return a value?
‣ What if a class re-implements superclass methods?
‣ What happens when no method is found?
‣ What is the difference between super and self?
Michele Lanza 45 Smalltalk in a Nutshell
46. What if a class reimplements superclass methods?
‣ The overridden method in the superclass will become
“invisible” to the object
‣ To access its behavior you must use “super”
‣ The best example is given by the #initialize methods
‣ What is the difference between self and super?
‣ A self send triggers a dynamic method lookup starting in the
class of the receiver
‣ A super send triggers a static method lookup starting in the
superclass of the class implementing the method performing
the super send
Michele Lanza 46 Smalltalk in a Nutshell
47. What happens when no method is found?
‣ Object is the root of the world, lookup stops here..
‣ The VM will then send the message “self
doesNotUnderstand: #foo”, where #foo is the selector of
the method that was not found
‣ The lookup will start again in the original object, but this
time we are looking for the method #doesNotUnderstand:
‣ If nothing is done about it, lookup will arrive again in the
class Object, whose implementation says: Throw an
exception and pop up the debugger!
‣ But...you can write your own emergency code by overriding
#doesNotUnderstand: in your classes..
‣ The implications are massive, but it’s out of scope here..
Michele Lanza 47 Smalltalk in a Nutshell
49. Objects communicate via messages
‣ All communication in Smalltalk has the form receiver
selector argument(s)
‣ 1+2
‣ linePrinter nextNode: macNode
‣ Packet send: ‘Packet went to ‘ to: #lpr
‣ Workstation withName: #mac1
Michele Lanza 49 Smalltalk in a Nutshell
50. Messages instead of keywords
‣ In most languages, basic operators and control
constructs are defined as language constructs and
(reserved) keywords
‣ In Smalltalk, there’s only messages sent to objects
‣ bitshift: (>>) is just a message sent to a number
10 bitShift: 2
‣ ifTrue: (if-then-else) is just a message sent to a boolean
(X > 1) ifTrue: [ Transcript show: ‘bigger’ ]
‣ do:; to:do: (loops) are just messages sent to collections
of numbers
#(a b c d) do: [ :each | Transcript show: each; cr ].
1 to: 10 do: [ :i | Transcript show: i printString; cr]
Michele Lanza 50 Smalltalk in a Nutshell
51. Message Syntax in a Bottle
‣ Every expression is a message send
‣ There are 3 types of messages
1. Unary messages
Transcript cr
5 factorial
25 squared
2. Binary messages 3 + 4
5 * 6
3. Keyword messages Transcript show: ‘hello world’
2 raisedTo: 32
3 raisedTo: 10 modulo: 5
Michele Lanza 51 Smalltalk in a Nutshell
52. Precedence
‣ (...) > Unary > Binary > Keyword
1. Evaluate left-to-right
2. Unary messages have highest precedence
3. Next are binary messages
4. Keyword messages have lowest precedence
5. Use parentheses to change precedence
2 raisedTo: 1 + 3 factorial 128
1 + 2 * 3 9
1 + (2 * 3) 7
Michele Lanza 52 Smalltalk in a Nutshell
54. Metaclasses & Reflection in 7 points
‣ Every object is an instance of a class
‣ Every class eventually inherits from Object
‣ Every class is an instance of a metaclass
‣ The metaclass hierarchy parallels the class hierarchy
‣ Every metaclass inherits from Class and Behavior
‣ Every metaclass is an instance of Metaclass
‣ The metaclass of Metaclass in an instance of Metaclass
Michele Lanza 54 Smalltalk in a Nutshell
55. Every object is an instance of a class
‣ Implication: every object points
to its class
‣ If an object receives a message,
the object will “ask” its class how it
should act Student
‣ The behavior (== the methods) is
implemented in the class
‣
aStudent
The class also defines how much
space an object occupies
Michele Lanza 55 Smalltalk in a Nutshell
56. Every class eventually inherits from Object
‣ Student “is a” Person “is an” Object
‣ “is a” mean that if an object receives a
message, the method (in case it’s not
implemented in the object’s class) will be
looked up through the inheritance chain, if
necessary up until Object
‣ Object represents the common object
behavior
‣ Object does not have a superclass
Michele Lanza 56 Smalltalk in a Nutshell
57. Every class is an instance of a metaclass
‣ Classes are objects too!
‣ Every class X is the unique
instance of its metaclass called
X class
‣ Metaclasses are created
implicitly when a class is created
‣ There is no explicit metaclass
‣ You cannot share metaclasses
‣ They are unique to their class
Michele Lanza 57 Smalltalk in a Nutshell
58. A closer look at metaclasses...
Person subclasses
Person allSubclasses
DietPerson selectors
DietPerson allSelectors
DietPerson methodDictionary
Person allInstances
Person instVarNames
Person canUnderstand: #diet
Person allSubclasses do: [ :eachClass |
eachClass selectors do: [ :eachSelector |
Transcript show: eachClass name, '>>', eachSelector ; cr ]]
OrderedCollection(WWTutor,DietPerson,FMPlayer)
OrderedCollection(WWTutor,DietPerson,FMPlayer,WWPerson,SpagPerson)
IdentitySet (#diet)
<IdentitySet with 283 symbols)
MethodDictionary (#diet)
...
#('name' 'gender')
false
...
Michele Lanza 58 Smalltalk in a Nutshell
59. The metaclass hierarchy parallels the class hierarchy
‣ Uniformity between classes and
metaclasses
‣ Classes are objects too:
‣ Everything that holds for objects
holds for classes too
‣ Same method lookup strategy!
‣ ..but in the method dictionary of the
metaclass
‣ Imagine you would send new to
Student..what happens?
Michele Lanza 59 Smalltalk in a Nutshell
60. Every metaclass inherits from Class and Behavior
‣ Every class “is a “ class
‣ Every metaclass inherits from
Class who inherits eventually from
Behavior
‣ Behavior implements the minimum
state necessary for objects to have
instances
‣ Behavior is the basic interface to the
compiler and does things like
creating method dictionaries,
compiling methods, accessing
variables and instances, accessing
the class hierarchy (superclass,
subclasses, etc.)
‣ So...a quiz: Where is new defined?
Michele Lanza 60 Smalltalk in a Nutshell
61. Who defines new?
‣ Behavior... Behavior
‣ because it models the 7
behavior that a class Class-
Description
should have, and creating 6
an instance of a class is a Class
8
thing that a class should be quot;<<creates>>
5
able to do
Object
Object
class
4
Person
Person
class
Student 3
Student
class
1
2
new
aStudent
Michele Lanza 61 Smalltalk in a Nutshell
62. Every metaclass is an instance of Metaclass
‣ Metaclass represents common
metaclass behavior
‣ It is responsible for
‣ instance creation
‣ creating initialized instances of the
metaclass’ sole instance
‣ class information (inheritance link,
instance variables, etc.)
Michele Lanza 62 Smalltalk in a Nutshell
63. The metaclass of Metaclass is an instance of Metaclass
Michele Lanza 63 Smalltalk in a Nutshell
64. Meta-madness Quiz
“The class hierarchy” “The metaclass hierarchy”
Student superclass Student class class
= Person = Metaclass
Person superclass Person class class
= Object = Metaclass
Object superclass Object class class
= nil = Metaclass
“The parallel metaclass Class class class
hierarchy” = Metaclass
Student class name ClassDescription class class
= ‘Student class’ = Metaclass
Student class superclass Behavior class class
= Person class = Metaclass
Object class superclass Metaclass superclass
= Class = ClassDescription
Class superclass Metaclass superclass superclass
= ClassDescription = Behavior
ClassDescription superclass “The fixpoint”
= Behavior Metaclass class class
Behavior superclass = Metaclass
= Object
Michele Lanza 64 Smalltalk in a Nutshell
66. A Glimpse of Style
‣ There is much more to say & learn about Smalltalk
‣ We did not even scratch the surface of reflection
‣ There is a reason why most of the important recent
innovations in software development came through
Smalltalk
‣ But it’s impossible to convey that in 90 minutes..
‣ If you are intrigued grab an ESUG DVD and play with it
‣ Then come & talk to me and my research group
[ you areStillInterested ]
ifTrue: [ come and: [ talk to: me or: [ my group ]]]
ifFalse: [ bother not ]
Michele Lanza 66 Smalltalk in a Nutshell