67
Smalltalk in a Nutshell Michele Lanza

Smalltalk In a Nutshell

Embed Size (px)

Citation preview

Page 1: Smalltalk In a Nutshell

Smalltalk in a NutshellMichele Lanza

Page 2: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

Contents‣ Introduction‣ Origins of Smalltalk‣ Key Concepts‣ The Smalltalk Object Model‣ Messages‣ Metaclasses & Reflection‣ Conclusion

2

Page 3: Smalltalk In a Nutshell

Smalltalk in a NutshellMichele Lanza

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

3

Page 4: Smalltalk In a Nutshell

Introduction

what is Smalltalk?

Page 5: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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

5

Page 6: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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

6

Page 7: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

Death Match Smalltalk C++ Java

Object model

Garbage collection

Inheritance

Type System

Reflection

Concurrency

Modules

Pure Hybrid Hybrid

Automatic Manual Automatic

Single Multiple Single + Interfaces

Dynamic Static Static

Fully reflective Introspection Introspection

Semaphores, Monitors Some libraries.. Monitors

Categories, namespaces, bundles, packages, ...

Namespaces Packages

Smalltalk vs. C++ vs. Java

7

Page 8: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

Platform Details

Visualworks

ObjectStudio

Squeak

Gemstone/S

Dolphin

Smalltalk X

GNU Smalltalk

VisualAge

Unix, Linux, Windows, Mac

based on Xerox PARC specs, but highly optimized. Binary cross-platform

Windows, Mainframes

similar to VisualWorks, one day they will merge

everything, everything

free and open, based on the ST-80 specs. Effort started by Kay with a focus on Multimedia

Unix, Linux, Windows

server-side, persistent, multi-user, active ODBMS

Windows native widgets, tight integration with Windows.Was free, became commercial, now free again

Unix, Linux, Windows

splendid implementation of the ANSI standard

Unix, Linux, Windows

free, well-versed for scriptingmaintained by our very own Paolo Bonzini :-)

Unix, Windows, OS/2 cross-platform via source, percursor to Eclipse

Smalltalk Implementations

8

Page 9: Smalltalk In a Nutshell

Smalltalk in a NutshellMichele Lanza

Community

‣ European Smalltalk User Group‣ esug.org

‣ Squeakworld‣ squeak.org

‣ Smalltalk Industry Council‣ stic.org

9

Page 10: Smalltalk In a Nutshell

Smalltalk in a NutshellMichele Lanza

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

10

Page 11: Smalltalk In a Nutshell

The Origins

dealers of lightnings

Page 12: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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”

12

Page 13: Smalltalk In a Nutshell

Smalltalk in a NutshellMichele Lanza

‣ 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.

Xerox PARC

13

Page 14: Smalltalk In a Nutshell

Smalltalk in a NutshellMichele Lanza

http://www.artmuseum.net/w2vr/archives/Kay/01_Dynabook.html

The Dynabook & The Alto

14

‣ The Dynabook, Kay’s vision of a laptop for children

‣ The Alto, a machine to run Smalltalk‣ Precursor to Apple’s Lisa

Page 15: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

The Good Old Days...

15

Page 16: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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

16

Page 17: Smalltalk In a Nutshell

Key Concepts

power & simplicity

Page 18: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

“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 "How does this work?" with "I don’t care"“.

Alan Knight, Smalltalk Guru

This is weird...

18

Page 19: Smalltalk In a Nutshell

Smalltalk in a NutshellMichele Lanza

‣ 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!

The Smalltalk “Image”

19

The image

Smalltalk Java

Edit- and Run-time Edit-time Run-time

Ha

rdw

are

In

de

pe

nd

en

ce

Ha

rdw

are

De

pe

nd

en

ce

Computer Hardware

Smalltalk Virtual Machine Java Virtual Machine (JVM)

Byte-code

Byte-code(*.class or *.jar)

Source-code

Source-code(*.java)

Page 20: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

exampleWithNumber: x

“A method that illustrates every p

art of Smalltalk method syntax

except primitives. It has unary, b

inary, and key word messages,

declares arguments and temporaries

(but not block temporaries),

accesses a global variable (but no

t an instance variable), uses

literals (array, character, symbol

, string, integer, float), uses

the pseudo variable true false, ni

l, self, and super, and has

sequence, assignment, return and c

ascade. 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);

show: ‘ ‘].

^ x < y

Syntax on a post card

20

Page 21: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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:

Smalltalk syntax in a nutshell

21

Page 22: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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++

22

Page 23: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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!

23

Page 24: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

Defining Classes & Variables‣ Edit the class creation template

24

class name

superclass name

instance variables

Page 25: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

Defining Methods: Fill in the template

‣ Smalltalk methods always return the object they belong to, unless specified otherwise

25

Page 26: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

Let’s see this Smalltalk thingy!

26

Page 27: Smalltalk In a Nutshell

Smalltalk in a NutshellMichele Lanza

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

27

Page 28: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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

28

[ :arg1 :arg2 | | temp1 temp2 | expression. expression ]

|sqr|sqr := [ :n | n*n].sqr value: 5

[:x :y | x + y + 3 ] value: 3 value: 4

Page 29: Smalltalk In a Nutshell

Smalltalk in a NutshellMichele Lanza

Booleans

‣ Slick implementation

‣ true and false are unique instances of True and False

‣ Lazy evaluation with and: and or:

‣ Blocks and Booleans are Crucial for the implementation of loops

29

ifTrue:IfFalse:not&

Boolean

ifTrue:IfFalse:

not

&

True

ifTrue:IfFalse:

not

&

False

...

...

Object

false and: [ 1 / 0 ]10 odd ifTrue: [ .. ] ifFalse: [ .. ]

Page 30: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

Looping Madness‣ Various kinds of loops are possible

‣ But loops without Collections are just half as fun..

30

| 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 ].

Page 31: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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...

31

Collection

ByteString

String

Symbol

Object

Set

Dictionary

IdentityDictionaryArray Text

Bag

SortedCollection

Heap

LinkedListArrayedCollection

Interval

SequenceableCollection

OrderedCollection

Page 32: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

Classic Ways to Iterate

32

aCollection do: aOneParameterBlock#(15 10 19 68) do: [ :each | Transcript show: each printString; cr ]

aCollection collect: aOneParameterBlock#(15 10 19 68) collect: [ :i | i odd ] PrintIt => #(true false true false)

aCollection with: anotherCollection do: aBinaryBlock#(1 2 3) with: #(10 20 30) do: [:x :y | Transcript show: (y * x) printString; cr ]

aCollection select: aOneParameterPredicateBlock#(15 10 19 68) select: [ :n | n odd ] => PrintIt => #(15 19)

aCollection reject: aOneParameterPredicateBlock#(15 10 19 68) reject: [ :i | i odd ] => PrintIt => #(10 68)

aCollection detect: aOneParameterPredicateBlock#(12 10 19 68 21) detect: [ :j | j odd ] => PrintIt => 19

aCollection detect: aOneParameterPredicateBlock ifNone: aBlock#(12 10 16 68) detect: [ :j | j odd ] ifNone: [ ‘no odd stuff here’] => PrintIt => ‘no odd stuff here’

More cool stuff: #includes:, #size, #isEmpty, #contains: #anySatisfy

Page 33: Smalltalk In a Nutshell

Break

Page 34: Smalltalk In a Nutshell

The Smalltalk Object Model

everything is an object

Page 35: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

The Smalltalk Object Model‣ Simple & uniform‣ everything is an object‣ objects communicate by sending each other messages

‣ The rules of the model1. Everything is an object2. Every object is an instance of a class3. Every class has a superclass4. Everything happens by message sends5. Method lookup follows the inheritance chain

35

Page 36: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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!

36

Page 37: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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

37

1 class -> SmallInteger20 factorial class -> LargePositiveInteger‘hello’ class -> ByteString#(1 2 3) class -> Array(4@5) class -> PointObject new class -> Object

Page 38: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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

38

Page 39: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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..

39

Page 40: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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

40

Page 41: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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

41

Page 42: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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

42

Page 43: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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!

43

Page 44: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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

44

Page 45: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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?

45

Page 46: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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

46

Page 47: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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..

47

Page 48: Smalltalk In a Nutshell

Messages

receiver selector argument(s)

Page 49: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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

49

Page 50: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

‣ 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

‣ ifTrue: (if-then-else) is just a message sent to a boolean

‣ do:; to:do: (loops) are just messages sent to collections of numbers

10 bitShift: 2

(X > 1) ifTrue: [ Transcript show: ‘bigger’ ]

#(a b c d) do: [ :each | Transcript show: each; cr ].1 to: 10 do: [ :i | Transcript show: i printString; cr]

Messages instead of keywords

50

Page 51: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

‣ Every expression is a message send‣ There are 3 types of messages1. Unary messages

2. Binary messages

3. Keyword messages

Transcript cr5 factorial25 squared

3 + 45 * 6

Transcript show: ‘hello world’2 raisedTo: 323 raisedTo: 10 modulo: 5

Message Syntax in a Bottle

51

Page 52: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

2 raisedTo: 1 + 3 factorial 128

1 + 2 * 3 9

1 + (2 * 3) 7

Precedence‣ (...) > Unary > Binary > Keyword1. Evaluate left-to-right2. Unary messages have highest precedence3. Next are binary messages4. Keyword messages have lowest precedence5. Use parentheses to change precedence

52

Page 53: Smalltalk In a Nutshell

Metaclasses & Reflection

elegance & uniformity

Page 54: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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

54

Page 55: Smalltalk In a Nutshell

Smalltalk in a NutshellMichele Lanza

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

‣ The behavior (== the methods) is implemented in the class

‣ The class also defines how much space an object occupies

55

aStudent

Student

Page 56: Smalltalk In a Nutshell

Smalltalk in a NutshellMichele Lanza

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

56

Page 57: Smalltalk In a Nutshell

Smalltalk in a NutshellMichele Lanza

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

57

Page 58: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

A closer look at metaclasses...

58

Person subclassesPerson allSubclassesDietPerson selectorsDietPerson allSelectorsDietPerson methodDictionaryPerson allInstancesPerson instVarNamesPerson canUnderstand: #dietPerson 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...

Page 59: Smalltalk In a Nutshell

Smalltalk in a NutshellMichele Lanza

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?

59

Page 60: Smalltalk In a Nutshell

Smalltalk in a NutshellMichele Lanza

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?60

Page 61: Smalltalk In a Nutshell

Smalltalk in a NutshellMichele Lanza

Who defines new?

‣ Behavior...‣ because it models the

behavior that a class should have, and creating an instance of a class is a thing that a class should be able to do

61

Student

class

Person

class

Object

class

aStudent

Student

Person

Object

Class

Class-

Description

Behavior

new

"<<creates>>

12

3

4

5

6

7

8

Page 62: Smalltalk In a Nutshell

Smalltalk in a NutshellMichele Lanza

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.)

62

Page 63: Smalltalk In a Nutshell

Smalltalk in a NutshellMichele Lanza

The metaclass of Metaclass is an instance of Metaclass

63

Page 64: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

Meta-madness Quiz

64

“The class hierarchy”Student superclass= PersonPerson superclass= ObjectObject superclass= nil“The parallel metaclass hierarchy”Student class name= ‘Student class’Student class superclass= Person classObject class superclass= ClassClass superclass= ClassDescriptionClassDescription superclass= BehaviorBehavior superclass= Object

“The metaclass hierarchy”Student class class= MetaclassPerson class class= MetaclassObject class class= MetaclassClass class class= MetaclassClassDescription class class= MetaclassBehavior class class= MetaclassMetaclass superclass= ClassDescriptionMetaclass superclass superclass= Behavior“The fixpoint”Metaclass class class = Metaclass

Page 65: Smalltalk In a Nutshell

Conclusion

beauty and the beholder

Page 66: Smalltalk In a Nutshell

Smalltalk in a Nutshell Smalltalk in a NutshellMichele Lanza

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

66

[ you areStillInterested ] ifTrue: [ come and: [ talk to: me or: [ my group ]]]ifFalse: [ bother not ]

Page 67: Smalltalk In a Nutshell

The End

thank you