0% found this document useful (0 votes)
200 views12 pages

Overview of Smalltalk Programming

Smalltalk was the first object-oriented programming language and graphical user interface, developed at Xerox PARC in the 1970s. It influenced Steve Jobs and the creation of the Macintosh. Smalltalk uses objects, messages, and classes to implement object-oriented programming principles like inheritance and polymorphism. Programming in Smalltalk involves defining classes, implementing methods, and evaluating expressions in an interactive development environment.

Uploaded by

Nawij Itrahg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
200 views12 pages

Overview of Smalltalk Programming

Smalltalk was the first object-oriented programming language and graphical user interface, developed at Xerox PARC in the 1970s. It influenced Steve Jobs and the creation of the Macintosh. Smalltalk uses objects, messages, and classes to implement object-oriented programming principles like inheritance and polymorphism. Programming in Smalltalk involves defining classes, implementing methods, and evaluating expressions in an interactive development environment.

Uploaded by

Nawij Itrahg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Topics

Smalltalk
 History and significance of Smalltalk
 Object-oriented programming

The best way to predict the future is to  The Smalltalk language

invent it.  Smalltalk today


 Additional Examples
Alan Kay, 1971

 Alan Kay coined the term “object


History of Smalltalk oriented”

 Smalltalk was developed at the Xerox Palo “…and I can tell you I did not have C++ in mind.”
Alto Research Center (PARC) in the early
1970’s  2004 Turing Award Winner
 Alan Kay, Dan Engalls, Adele Goldberg,
Dave Robson
 Delivered the Turing Lecture at OOPSLA
2004

OOP and GUI Steve Jobs, PARC, Dec 1979


 Smalltalk was the first object-oriented And they showed me really three things. But I was so blinded by the
first one I didn't even really see the other two. One of the things they
programming (OOP) language and the first showed me was object oriented programming; they showed me that
but I didn't even see that. The other one they showed me was a
graphical user interface (GUI) networked computer system...they had over a hundred Alto
computers all networked using email etc., etc., I didn't even see that.
I was so blinded by the first thing they showed me which was the
graphical user interface. I thought it was the best thing I'd ever seen
 Gave Steve Jobs the idea for the in my life. Now remember it was very flawed, what we saw was
MacIntosh incomplete, they'd done a bunch of things wrong. But we didn't
know that at the time but still though they had the germ of the
idea was there and they'd done it very well and within you know
ten minutes it was obvious to me that all computers would work
like this some day.

Smalltalk 1
Object-
Object-Oriented Programming OOP
 Object: encapsulates data describing  Inheritance: reuse of classes by
something (often an object in the real specializing general behavior
world) as well as methods (or programs)  Polymorphism: many different objects can
that manipulate that data respond to the same message
 Message: communication between objects;  Dynamic Binding: resolution of message
method invocations binding is deferred until runtime
 Class: defines structure and common
behavior of a group of objects

OOP Smalltalk Implementations


 Combination of inheritance with  Smalltalk is written mostly in Smalltalk
polymorphism and dynamic binding
provides a powerful form of genericity
 The core of any Smalltalk implementation
is a small bytecode interpreter (virtual
 Allows high levels of reuse, fast
development machine)
 Smalltalk source code is compiled to
 BUT: “Even if you only want the banana, intermediate bytecode to be executed on
you have to take the whole gorilla.” the VM

Programming in Smalltalk Objects


 have local memory, inherent processing
 Programming in Smalltalk involves capability, capability to communicate with
– Defining classes other objects.
– Implementing class methods  Examples:
– Evaluating expressions 2 True
FileStream Text Editor
 Most Smalltalk languages provide an Class MetaClass
interactive GUI as a development  Can be passed as parameters and returned as
environment results

Smalltalk 2
Messages and Methods Classes and Instances
 Class: The abstract definition of the
 Message: a request to an object to perform behavior of a class of objects
an operation (analogous to function call)
 Method: implementation of an operation  Instance: an individual object defined by a
(function) class
 Examples of messages:
‘hello, world’ size
#(1 12 24 36) includes: 4 factorial
3 < 4 ifTrue: [‘Yes’] ifFalse: [‘No’]

Instance methods and Class methods Instance variables


 Instance method: a method that describes  Instance variables: a variable that stores
how an operation is carried out by every data for an instance of a class
instance of a class
 Class method: a method that describes how  Generally have different values for each
an operation is carried out by a class, such instance
as creating a new instance of itself.
Class methods are sent to the class (an  The collection of instance variables
instance of Class MetaClass) rather than to describes the state of the object
an instance of the class

Class variables Inheritance


 A variable that is shared by a class and all
of its instances  Classes are arranged in a hierarchy
Superclass: the parent of a class
 Available to all instances of a class Subclass: a child of a class

 Can be constants (Float pi) or even  Subclasses inherit the variables and
references to existing instances, such as methods of the superclass
Students class that maintains a list of
Student instances

Smalltalk 3
The Magnitude Class Hierarchy
Inheritance in Smalltalk Magnitude
Association
 Is a strict tree structure: a subclass can Character
have one and only one parent class Date
Number
Float
 Subclasses usually “specialize” the more Fraction
general behavior of the parent class Integer
– Can add new variables or methods LargeInteger
SmallInteger
– can also hide inherited functionality
Time

The Collection Class Hierarchy Another Collection Hierarchy


Collection
Bag
IndexedCollection
FixedSizeCollection
Array
Bitmap
ByteArray
CompiledMethod
Interval
String
Symbol
OrderedCollection
Process
SortedCollection
Set
Dictionary

22

Expressions
 Smalltalk does not have a “statement” in the
Literals and Variables
sense used by procedural languages
 Computation is achieved by evaluating  Literals
expressions
#aSymbol #(1 2 4 16 32 64)
 All expressions return an object
‘Hello, World’
 Types:
– Literals
– Variable names  Variables
– Message expressions Smalltalk x selectedDictionary
– Blocks of code

Smalltalk 4
Variables Public and Private Variables
 Names are syntactically similar to other  Public variables are shared and visible
languages globally
 All variables are pointers to objects Name begins with upperclass letter
 All variables are inherently typeless  Private variables are local to an object,
No difference between pointing to the number block or method
42 and pointing to an instance of a text editor – Name begins with lowerclass letter

Message Expressions Message Expression Examples


set add: stream next
 Sending a message involves: (receiver is set, selector is add, argument is result of
stream next, where receiver is stream and next is
– object to which message is sent (“receiver”) selector)
– additional objects included in message 2 + 3
(“arguments”) (receiver is 2, selector is +, argument is 3)
– desired operation to be performed (“message
selector”) array at: index + offset put: Bag new

– Accepting the single object returned as the array at: 1 put: self
“message answer”

Message Syntax Types Message Syntax Types

 Unary (no parameters)  Keyword (a general extension of infix


firstAngle cos syntax)
42 PrintString myArray at: 42 put: 5
 Binary (selector is “at: put:”)
2 + 3  In practice very few methods accept more
thisCollection = thatCollection than 2 parameters

Smalltalk 5
Selector Evaluation Order Cascading Messages
 A series of messages sent to same object
 Rules are a bit odd unless you are used to
APL myPen home; up; goto: 100@200; down; home
 Unary and binary expressions associate left
to right Equivalent to:
12 - 3 * 3 -> 27 myPen home
12 - (3 * 3) -> 3 myPen up
12 - 12 sin * 3 -> 0 myPen goto: 100@200
myPen down
myPen home

Method Definitions Self references


 Often an object needs to send a message to itself
 General Syntactic Form
MessagePattern  Pseudovariable "self" is used to refer to the
object itself
| local variables |
Expressions
 Examples:
 Return object designated with ^ count = 0
 An object can refer to itself with self ifTrue: [self error:
"0 items being averaged"]
ifFalse: [ ^sum / count]

Self references Unary method example


 Fibonacci numbers
fibonacci left
"Answer the nth fibonacci number, where "return the left subtree of the
n is the receiver" receiver"
^self < 3
ifTrue: [1] ^ self left
ifFalse: [(self-1) fibonacci +
(self-2) fibonacci]
Testing fibonacci
#(1 2 3 4 5 6 7 10 30)
collect: [:m | m fibonacci]

Smalltalk 6
Binary method example index := self size
index ~= aCollection size
= aCollection
ifTrue: [^false]
"answer true if elements contained by
receiver are equal to the elements [index <= 0]
contained by aCollection " whileFalse: [
| index | (self at: index) = aCollection at: index)
self == aCollection ifFalse: [^false].
ifTrue: [^true]. index := index – 1.]
(self class == aCollection class) ^true
ifFalse: [^false].
Note: == is equivalence (test for same object)
while = is test for equality (equal values)

Keyword method example Assignment


setX: xCoord setY: yCoord setZ: zCoord  Syntactically similar to other languages, but
"set coordinates for a threeDpoint" variables are “typeless”
x := xCoord
y := yCoord
z := zCoord  | x |
^self x := 1
x := “A String”
x := Pen new.

Control Structures Blocks


 Smalltalk has NO conventional control  Objects consisting of a sequence of
structures expressions
[index := index + 1. sum := sum + index.]
 Expression are evaluated when block
 Control structures are formed by passing receives the message “value”
block objects as parameters to Boolean [index := index + 1.
objects sum := sum + index.] value
 Blocks can be assigned to variables and
executed by sending the message "value" to
the variable.

Smalltalk 7
Iteration Iteration
count := 0.
sum := 0. "copy a disk file"
[ count <= 20 ] | input output |
whileTrue: [ sum := sum + count. input : = File pathName: 'go'.
count := count + 1 ] output := File pathName: 'junk'.
 WhileTrue: is a method of Class Boolean
[input atEnd]
whileFalse: [output nextPut: input next],
value is a method of Class Block
input close,
whileTrue: sends message "value" to conditional block output close
Conditional block returns object true or false
If results is true, WhileTrue: evaluates code in parameter
block

44

For loop (to: by:) Selection


 Similar to iteration. Common control structures
"compute the sum of 1/2, 5/8, 3/4, 7/8, 1" ifTrue:
| sum | if False:
ifTrue: ifFalse:
sum := 0.
1/2 to: 1 by: 1/8 total = 0
do: [ :i | sum := sum + i] . ifTrue: [average := 0]
^sum ifFalse: [average := sum / total]
 Message "= 0" sent to object total
returns either True or False
resulting Boolean object is receiver of ifTrue: message

45

Block Parameters Classes


 Blocks can accept parameters  All Smalltalk objects are instances of
[:x :y | (x * x) + (y * y).] classes (including classes: they are
instances of class MetaClass)
[:x :y | (x * x) + (y * y).]
 A Class definition has four parts:
value: 2 value: 3
-> 13 – Class name
– Superclass name
– declaration of local (instance) variables
– a set of methods that define how instances will
respond to messages

Smalltalk 8
Classes and Message Lookup Polymorphism
 A message sent to an object causes lookup  Polymorphism: a specific message may be
in class definition sent to different instances of different class
 If search fails, then lookup proceeds to at different times
superclass
 Top of hierarchy is class Object  Method lookup in Smalltalk occurs at
 If no method found, error results execution time

 Allows unlimited polymorphism since any


class can implement any method

Polymorphism Type Checking


 Consider a + b - c  Variables are typeless and can be bound to
The methods + and - could be implemented by class any object
String with an arbitrary meaning.
 Type checking is performed dynamically
 a + b
when message sent to object
– string concatenation-returns a with b concatenated
 If object lacks a method to respond to the
 b – c
– returns b with all occurrences of c removed
message, lookup proceeds to superclass
 Then a + b - c would first remove all All the way up to class Object
occurrences of c from b, then concatenate the Failure at this point results in error
result to a (if a, b and c are instances of String)

A Stack
Inheritance class name
superclass name
Stack
Object
instance variable names stack
 A subclass inherits all of the instance variables,
instance methods and class methods of the "Class Methods"
superclass new
– New instance variables can be added "Create an instance"
stack = OrderedCollection new.
– Names must differ from names of instance variables
^self
in ancestor classes
 A subclass can define new methods or redefine "Instance Methods"
methods implemented in an ancestor class pop
"Answer the receiver with last item removed from
 Redefinition hides definition in ancestor class stack"
 Pseudovariable "super" can be used in methods self size = 0
to refer method search to the superclass ifTrue: [self error: "Attempt to pop empty
stack"]
ifFalse: [stack removeFirst. ^self]

Smalltalk 9
push: anItem Another Stack
"Answer the receiver with anItem added to the class name Stack
top"
stack addFirst: anItem. superclass name OrderedCollection
^self instance variable names none
"Class Methods"
top new
"Answer the top item on the receiver" "Create an instance"
^self size = 0 ^super new.
ifTrue: [self error: "Attempt to take top of pop
empty stack"]
^self removeFirst
ifFalse: [^stack at: 1]
push: anItem
empty ^self addFirst: anItem
"Answer true if the receiver is empty" top
^self size = 0 ^self at: 1
empty
size ^self size = 0
"Answer the size of the receiver"
^stack size

Designing a class hierarchy is not easy…


easy… Smalltalk Today
 Problem with stack implementation as  "The best way to predict the future is to
subclass of OrderedCollection: invent it.“ (Alan Kay, 1971)
myStack:= Stack new.
1 to: 10 do: [ :x | myStack push: x]
middle := myStack at: 5  Smalltalk is the origin of two of the most
important computing “developments” of the
last two decades:
 Need to hide “inappropriate” methods of – Object Oriented Programming (OOP)
OrderedCollection
– Graphical User Interfaces (GUIs)

Smalltalk Today Smalltalk Resources


 Smalltalk still has a small but enthusiastic
following  Most prominent open-source version is
 Often used in industry as a rapid prototyping Squeak Smalltalk
environment  See [Link]
 IBM (VisualAge Smalltalk) promotes it as  [Link]( [Link] )
an e-commerce tool has a comprehensive list of products and
 OOVM has developed a Smalltalk VM for many interesting articles and tutorials
embedded systems that does not need an OS
 Implemented in MS .NET 2003 as S#

Smalltalk 10
Of interest to Ruby users: 99 Bottles of Beer
"Copy into a workspace, highlight the code and choose do
 Ruby The Smalltalk Way it."
"Tested under Squeak 3.7 and VisualWorks 7.3"
[Link] | verseBlock |
verseBlock := [ :bottles | | verse |
verse := WriteStream with: (String new).
bottles = 0 ifTrue:
[verse
nextPutAll: 'No more bottles of beer on the wall.
No more bottles of beer...'; cr;
nextPutAll: 'Go to the store and buy some more...
99 bottles of beer.'; cr].
bottles = 1 ifTrue:

61 62

[verse
nextPutAll: '1 bottle of beer on the wall. 1 bottle of
beer...'; cr;
nextPutAll: 'Take one down and pass it around, no more
bottles of beer on the wall'; cr].
bottles > 1 ifTrue:
Example: Polynomials
[verse
nextPutAll: bottles printString; nextPutAll: ' bottles
of beer on the wall. ';
nextPutAll: bottles printString; nextPutAll: ' bottles
of beer...'; cr;
 Polynomials
nextPutAll: 'Take one down and pass it around, ';
nextPutAll: (bottles - 1) printString, ' bottle';
– Represent Polynomials such 3x2 + 5x - 7
nextPutAll: (((bottles - 1) > 1)
ifTrue: ['s '] ifFalse: [' ']); – Representation is a collection of coefficients:
nextPutAll: 'of beer on the wall'; cr].
verse contents]. #(-7 5 3)
99 to: 0 by: -1 do: – Subclass of Magnitude
[: i | Transcript show: (verseBlock value: i); cr].

 For the true OO version of 99 Bottles, see


[Link]
63 64

degree
"Highest non-zero power"
Polynomial class ^ coefficient size - 1

Magnitude subclass: #Polynomial coefficient: power


instanceVariableNames: 'coefficient' "Coefficient of given power"
classVariableNames:: '' (power >= coefficient size) ifTrue: [ ^ 0 ].
poolDictionaries: '' ^ coefficient at: power + 1

new asArray
"Unary class constructor: return 0*x^0" ^ coefficient deepCopy
^ self new: #( 0 )
= aPoly
new: array ^ coefficient = aPoly asArray
"Keyword class constructor"
^ (super new) init: array != aPoly
^ (self = aPoly) not
init: array
"Private: initialize coefficient" < aPoly
coefficient := array deepCopy 65 "not defined" 66
^ self shouldNotImplement

Smalltalk 11
Complex class
Evaluate method Object Subclass: #Complex
instanceVariableNames: 'realpart imagpart'
classVariableNames:: ''
evaluate: aPolynomial x: aNumber poolDictionaries: ''
"Return the results of evaluating aPolynomial new
for the value aNumber" "Unary class constructor: Invalid"
^ self error 'use real:imaginary:'
| index val | new: aComplex
index := 1 "Class constructor aComplex"
val := 0 ^ (super new) copy: aComplex
[index < coefficient size] whileTrue:
real: r imaginary: i
[ val := val + (coefficient at: index) *
"Class Constructor"
(aNumber raisedToInteger: (index – 1)) ] ^ (super new) setReal: r setImaginary: i
^ val
setReal: r setImaginary: i
"Private instance method to initialize self"
realpart := r
imagpart := i
67 68
^self

real
"Return real part"
^ realpart
negated
"Return new complex number: - self"
imaginary
^ Complex real: realpart negated imaginary:
"Return imaginary part" imagpart negated
^ imagpart
= val
+ val "Return self = val"
"Return new complex number: self + val" ^ (realpart = val real) & (imagpart = val
^ Complex real: realpart + val real imaginary)
imaginary: imagpart + val imaginary
< val
- val "Not mathemtically defined"
"Return new complex number: self - val" ^ self shouldNotImplement
^ Complex real: realpart - val real
imaginary: imagpart - val imaginary
69 70

Smalltalk 12

You might also like