Smalltalk Lecture 1
1
Why Smalltalk?
> Pure object-oriented language and environment ¡ª ¡°Everything is an object¡±
> Origin of many innovations in OO development ¡ª RDD, IDE, MVC, XUnit …
> Improves on many of its successors ¡ª Fully interactive and dynamic
2
What is Smalltalk?
> Pure OO language ¡ª Single inheritance ¡ª Dynamically typed
> Language and environment
¡ª Guiding principle: ¡°Everything is an Object¡±
¡ª Graphical Smalltalk implementations have class browser, debugger, inspector, …
¡ª Mature class library and tools
> Virtual machine
¡ª Objects exist in a persistent image [+ changes] ¡ª Incremental compilation
3
Smalltalk vs. C++ vs. Java
Object model
Garbage collection
Inheritance
Types
Reflection
Concurrency
Modules
Smalltalk
Pure
Automatic
Single
Dynamic
Fully reflective
Semaphores, Monitors
Categories, namespaces
C++
Hybrid
Manual
Multiple
Static
Introspection
Some libraries
Namespaces
Java
Hybrid
Automatic
Single
Static
Introspection
Monitors
Packages
4
Smalltalk: a State of Mind
> Small and uniform language
¡ª Syntaxfitsononesheetofpaper
> Large library of reusable classes
¡ª Basic Data Structures, GUI classes, Database Access, Internet,
Graphics
> Advanced development tools
¡ª Browsers,GUIBuilders,Inspectors,ChangeManagementTools,
Crash Recovery Tools, Project Management Tools
> Interactive virtual machine technology ¡ª Trulyplatform-independent
> Team Working Environment
¡ª Releasing,versioning,deploying
5
Origins of Smalltalk
> Project at Xerox PARC in 1970s
¡ª Language and environment for new generation of graphical
workstations (target: ¡°Dynabook¡±)
> In Smalltalk-72, every object was an independent entity
¡ª Language was designed for children (!)
¡ª Evolved towards a meta-reflective architecture
> Smalltalk-80 is the standard
6
Precursor, Innovator & Visionary
> First to be based on Graphics
¡ª Multi-Windowing Environment (Overlapping Windows)
¡ª Integrated Development Environment: Debugger, Compiler, Text Editor, Browser
> With a pointing device (yes, a Mouse)
> Ideas were taken over ¡ª Apple Lisa, Mac
¡ª Microsoft Windows 1.0
> Platform-independent Virtual Machine
> Garbage Collector
> Just-in-time Compilation
> Everything was there, the complete Source Code
7
What are Squeak and Pharo?
> We will use text-based GNU Smalltalk in this course
> Encourage you to also look at graphical-based Smalltalk
implementations
> Squeak is a modern, open-source, highly portable, fast, full-featured Smalltalk implementation
¡ª Based on original Smalltalk-80 code
> Pharo is a lean and clean fork of Squeak ¡ª www.pharo-project.org
8
Squeak desktop
9
Smalltalk ¡ª Key Concepts
> Everything is an object
¡ª numbers, files, editors, compilers, points, tools, booleans …
> Everything happens by sending messages
> Every object is an instance of one class
¡ª which is also an object
¡ª A class defines the structure and the behavior of its instances.
> Objects have private (protected) state ¡ª Encapsulation boundary is the object
> Dynamic binding
¡ª Variables are dynamically typed and bound
10
Objects and Classes
> Every object is an instance of a class
¡ª A class specifies the structure and the behaviour of all its
instances
¡ª Instances of a class share the same behavior and have a specific state
¡ª Classes are objects that create other instances
¡ª Metaclasses are classes that create classes as instances
¡ª Metaclasses describe class behaviour and state (subclasses, method dictionary, instance variables…)
11
Messages and Methods
> Message ¡ª which action to perform
aWorkstation accept: aPacket aMonster eat: aCookie
> Method ¡ª how to carry out the action
accept: aPacket [
(aPacket isAddressedTo: self)
]
ifFalse: [super accept: aPacket]
ifTrue:[
Transcript show:
‘A packet is accepted by the Workstation ‘, self name asString ]
12
Smalltalk Run-Time Architecture
> Byte-code is translated to native code by a just-in-time compiler
¡ª Some Smalltalks, but not Pharo
> Source and changes are not needed to interpret the byte-code.
¡ª Just needed for development
¡ª Normally removed for deployment
> An application can be delivered as byte-code files that will be executed with a VM.
¡ª The development image is stripped to remove the unnecessary development components.
13
Objects in Smalltalk
> Everything is an object
¡ª Things only happen by message passing ¡ª Variables are dynamically bound
> State is private to objects ¡ª ¡°protected¡± for subclasses
> Methods are public
¡ª ¡°private¡± methods by convention only
> (Nearly) every object is a reference ¡ª Unused objects are garbage-collected
> Single inheritance
14
Smalltalk Syntax on a Postcard
exampleWithNumber: x [
“A method that illustrates every part of Smalltalk method syntax except primitives. It has unary, binary, and key word messages, declares arguments and temporaries (but not block temporaries), accesses a global variable (but not and instance variable),
uses literals (array, character, symbol, string, integer, float), uses the pseudo variable true false, nil, self, and super,
and has sequence, assignment, return and cascade. It has both zero argument and one argument blocks. It doesn¡¯t do anything useful, though”
|y|
true & false not & (nil isNil) ifFalse: [self halt]. y := self size + super size.
#($a #a ‘a’ 1 1.0)
do: [:each | Transcript show: (each class name); show: (each printString);
^ x < yshow: ' ']. ]
15
Language Constructs
^
return
"..."
comment
#
symbol or array
'...'
string
[]
block or byte array
.
statement separator
;
message cascade
|...|
local or block variable
:=
assignment (also _ or ¡û)
$_
character
:
end of selector name
_e_ _r_
number exponent or radix
!
file element separator (used in change sets)
16
Examples
comment:
“a comment”
character:
$c $h $a $r $a $c $t $e $r $s $# $@
string:
‘a nice string’
symbol:
#mac #+
array:
#(1 2 3 (1 3) $a 4)
dynamic array:
{ 1 + 2 . 3 / 4 . 5 * 6}
Integer:
72, 2r101
real:
1.5, 6.03e-34, 2.4e7
fraction:
1/33
boolean:
true, false
pseudo variables
self, super
point:
10@120
Note that @ is not an element of the syntax, but just a message sent to a number. This is the same for /, bitShift:, ifTrue:, do: …
17
Messages instead of keywords
> In most languages, basic operators and control constructs are defined as language constructs and keywords
> In Smalltalk, there are 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 to collections or numbers
> Minimal parsing
> Language is extensible
#(#a #b #c #d) do: [:each | Transcript show: each ; cr] 1 to: 10 do: [:i | Transcript show: i printString; cr]
18
Smalltalk Syntax
Every expression is a message send
> Unary messages
> Binary messages
> Keyword messages
Transcript cr
5 factorial
3 +4 5 *6
Transcript show: ‘hello world’
2 raisedTo: 32
segment fromX: 1 fromY: 1
toX: 50 toY: 100
19
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
2raisedTo:1+3factorial 128
5. Use parentheses to change precedence
9 (!) 7
1+2* 3 1 + (2 * 3)
20
Binary Messages
> Syntax:
¡ª aReceiver aSelector anArgument
¡ª Where aSelector is made up of 1 or 2 characters from:
+-/\*~<>=@%|&!?, ¡ª Except: second character may not be $
> Examples:
2 *3 – 5
5 >= 7
6 =7
‘hello’, ‘ ‘, ‘world’ (3@4) + (1@2)
2<<5 64>>5
21
More syntax
> Comments are enclosed in double quotes “This is a comment.”
> Use periods to separate expressions
Transcript cr.
Transcript show: ‘hello world¡¯.
Transcript cr “NB: don¡¯t need one here”
> Use semi-colons to send a cascade of messages to the same object
Transcript cr; show: ‘hello world’; cr
22
Variables
> Declare local variables with | … | | xy |
> Use := to assign a value to a variable x := 1
> Old fashioned assignment operator: ¡û (must type ¡°_¡±)
23
Method Return
> Use a caret to return a value from a method or a block
max: aNumber
^ self < aNumber
ifTrue: [aNumber]
ifFalse: [self]
1max:2 2
> Methods always return a value ¡ª By default, methods return self
24
Block closures
> Use square brackets to delay evaluation of expressions ^ 1 < 2 ifTrue: ['smaller'] ifFalse: ['bigger']
'smaller'
25
Variables
> Local variables within methods (or blocks) are delimited by |var|
> Block parameters are delimited by :var|
OrderedCollection>>collect: aBlock [
“Evaluate aBlock with each of my elements as the argument.”
| newCollection |
newCollection := self species new: self size. firstIndex to: lastIndex do:
[ :index |
newCollection addLast: (aBlock value: (array at: index))]. ^ newCollection
]
[:n | |x y| x := n+1. y := n-1. x * y] value: 10
99
26
Control Structures
> Every control structure is realized by message sends
|n|
n := 10.
[n>0] whileTrue:
[ Transcript display: n; cr. n:=n-1 ]
1 to: 10 do: [:n| Transcript display: n; cr ]
(1 to: 10) do: [:n| Transcript display: n; cr ]
27
Creating objects
> Class methods
> Factory methods
OrderedCollection new
Array new: 200
Array with: 10 with: 20 with: 30
1@2 “a Point” 1/2 “a Fraction”
28
Creating classes
> Send a message to a class (!)
Number subclass: #Complex
Complex instanceVariableNames: ‘real imaginary’
29
Some Conventions
> Method selector is a symbol, e.g., #add:
> Method scope conventions using >>
(for displaying the methods of a class) ¡ª Instance Method defined in the class Node
Node>>accept: aPacket
¡ª Class Method defined in the class Node class
(i.e., in the class of the the class Node)
Node class>>withName: aSymbol
> aSomethingisaninstanceoftheclassSomething
30
Example: Money (abstract Smalltalk syntax)
> We define Money as a subclass of Object, with getters and setters
Object subclass: #Money.
Money instanceVariableNames: ‘amount currency’.
Money>>amount: aNumber amount:= aNumber.
Money>>amount ^ amount
Money>>currency: aString currency := aString.
Money>>currency ^ currency
31
GNU Smalltalk syntax
> We define Money as a subclass of Object, with getters and setters
Object subclass: #Money.
Money instanceVariableNames: ‘amount currency’.
Money extend [
amount [ ^amount ]
amount: aNumber [ amount := aNumber ] currency [ ^currency ]
currency: aString [ currency := aString ]
].
32
Test cases
x := Money new currency: ‘USD’; amount: 100. y := Money new currency: ‘Euro’; amount: 500.
x amount printNl.
x currency printNl.
y amount printNl.
y currency printNl.
x amount: 999.
y currency: ‘Yen’.
x amount printNl.
x currency printNl.
y amount printNl.
y currency printNl.
“100”
“‘USD'”
“500”
“‘Euro'”
“999”
“‘USD'”
“500”
“‘Yen'”
33
Comparisons (binary operators)
Money>>= aMoney
^ self currency = aMoney currency and: [ self amount = aMoney amount ]
Money>>~= aMoney
^ (self = aMoney) not
Money extend [ “GNU Smalltalk syntax” = aMoney [
^ self currency = aMoney currency
] and: [ self amount = aMoney amount ]
~= aMoney [^ (self = aMoney) not]
].
34
More test cases
x := Money new currency: ‘USD’; amount: 100. y := Money new currency: ‘Euro’; amount: 500. z := Money new currency: ‘USD’; amount: 100.
(x = y) printNl.
(x ~= y) printNl.
(x = z) printNl.
(x ~= z) printNl.
“false”
“true”
“true”
“false”
35
Using GNU Smalltalk
> gst”evaluates Smalltalk code line-by-line” st> 2 + 3 * 4
20
st> “press control-D to exit interpreter”
> gst Money.st
“runs all the Smalltalk code in given file”
> gst
st> FileStream fileIn: ‘Money.st’
“loads and runs code in file, stays in gst” st>
36