Top Banner
An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian S.Jalal Kazemitabar Emad Livani University of Tehran – ECE Department Programming Languages Course, Fall 2004
143

An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Jan 27, 2016

Download

Documents

Shana

An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian S.Jalal Kazemitabar Emad Livani University of Tehran – ECE Department Programming Languages Course, Fall 2004. Smalltalk Quotes. Common languages are tools, Smalltalk is a piece of art. Alan Kay: - PowerPoint PPT Presentation
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

An Introduction to

SmalltalkFirst Pure Object Oriented Language

By:

Misagh Bagherian

S.Jalal Kazemitabar

Emad Livani

University of Tehran – ECE Department

Programming Languages Course, Fall 2004

Page 2: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Smalltalk Quotes

• Common languages are tools, Smalltalk is a piece of art.

• Alan Kay:

• Simple things should be simple. Complex things should be possible

Page 3: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Outline

• Motivation to Object-Oriented Programming

• Smalltalk History

• Structural Organization

• Classes and Subclasses

• Objects and Message Sending

• Implementation: Classes and Objects

• Syntax Overview

• Conclusions

Page 4: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Part 1

• Structured Programming• Object Orientation

– Objects– ADTs– Encapsulation

• Language Concepts• Smalltalk History• Why Smalltalk ?

Page 5: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Structured Programming

• Define tasks to be performed• Break tasks into smaller and smaller pieces

– Until you reach a size you can implement

• Define the data structures to be manipulated• Design how functions interact

– What's the input– What's the output

• Group functions into components – "units" or “modules“

• Write the code

Page 6: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Program Structure

• Program Structure in Structural Approach

Main Program

Sub-program Sub-program Sub-program

Sub-programSub-program

Page 7: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Abstract Data Types (ADTs)

• Main ideas:– Separate interface from implementation

• Example: – Sets have empty, insert, union, is_member?, …– Sets implemented as … linked list …

– Use type checking to enforce separation• Client program only has access to operations in

interface• Implementation encapsulated inside ADT construct

Page 8: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Object Oriented Programming

• First goal: Model the objects of the world– Noun-oriented

• (in contrast to verb-orientation in Structured Programming)

– Focus on the domain of the program

• Phases– Object-oriented analysis: Understand the domain

• Define an object-based model of it

– Object-oriented design: Define an implementation strategy

• Design the solution

– Object-oriented programming: Build it

Page 9: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Object Oriented Programming

• Primary object-oriented language concepts

– dynamic lookup – encapsulation– inheritance – sub typing

Page 10: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Objects

• An object consists of – hidden data

instance variables, also called member data

hidden functions also possible

– public operationsmethods or member functionscan also have public variables

in some languages

• Object-oriented program:– Send messages to

objects

hidden data

method1msg1

. . .. . .

methodnmsgn

Page 11: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Object Orientation

• Programming methodology– organize concepts into objects and classes – build extensible systems

• Language concepts– dynamic lookup– encapsulation– subtyping allows extensions of concepts– inheritance allows reuse of implementation

Page 12: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Dynamic Lookup

• In object-oriented programming,object message (arguments)

code depends on object and message

• In conventional programming,operation (operands)

meaning of operation is always the same

Fundamental difference between abstract data types and objects

Page 13: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Example

• Add two numbers x add (y)different add if x is integer, complex, etc.

• Conventional programming add (x, y)function add has fixed meaning

• Very important distinction:– Overloading is resolved at compile time, – Dynamic lookup at run time

Page 14: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Language concepts

• “dynamic lookup”– different code for different object– integer “+” different from real “+”

• encapsulation

• sub typing

• inheritance

Page 15: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

How’d we get from there to here?

• How did we move from structured to object-oriented?– Key ideas

• Master-drawings in Sketchpad• Simulation “objects” in Simula

– Alan Kay and his desire to make software better

• More robust• More maintainable• More scalable

Page 16: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Encapsulation

• Builder of a concept has detailed view

• User of a concept has “abstract” view

• Encapsulation separates these two views – Implementation code: operate on

representation– Client code: operate by applying fixed set of

operations provided by implementer of abstraction

message Object

Page 17: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Encapsulation

• How does it support our objectives?

– Models real world• examples: driving a car

– Reusability & Ease of use• other users need only know ‘interface’, not the

implementation

Page 18: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Comparison with ADTs

• Traditional (non-OO) approach to encapsulation is through abstract data types

• Advantage– Separate interface from implementation

• Disadvantage– Not extensible in the way that OOP is

Page 19: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Abstract Data Types (ADTs)

• Guarantee invariants of data structure– only functions of the data type have access to the

internal representation of data

• Limited “reuse”– Cannot apply queue code to pqueue, except by

explicit parameterization, even though signatures identical

– Cannot form list of points, colored points

• Data abstraction is important part of OOP, innovation is that it occurs in an extensible form

Page 20: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Alan Kay

• University of Utah PhD student in 1966– Read Sketchpad, Ported Simula

• Saw “objects” as the future of computer science

• His dissertation: Flex, an object-oriented personal computer– A personal computer was a radical idea

then– How radical?

"There is no reason anyone would want a computer in their home." (Ken Olsen, Digital Equipment Corp, 1977)

Page 21: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Alan Kay

• Alan C. Kay: ”In the 1990’s there will be millions of personal computers. They will be the size of notebooks of today, have high-resolution flat-screen reflective displays, weigh less than ten pounds, have ten to twenty times the computing and storage capacity of an Alto. Let’s call them Dynabooks. The purchase price will be about that of a color television set of the era, ...” (1971)

Page 22: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Alan Kay

• Alan Kay’s categorization of Programming Languages:

– Agglutination of Features• Cobol, PL/1, Ada, etc.

– Crystallization of Style• Lisp, APL, and Smalltalk

Page 23: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Alan Kay’s Insights

• “Computer” as collection of Networked Computers

• All software is simulating the real world• Biology as model for objects

– Bacterium has 120M of info, 1/500th of a Cell, and we have 10^13 of these in us

– What man-made things can scale like that?• Stick a million dog houses together to get a

skyscraper?• Internet does, but how can we make that the

norm?

Page 24: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Birth of Objects → Sketchpad

• Ivan Sutherland's Sketchpad, 1963

Page 25: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Birth of Objects → Sketchpad

• First object-oriented drawing program

• Master and instance drawings

– Draw a house– Make two instances– Add a chimney to the master– Poof! The instances grow a chimney

Page 26: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Birth of Objects → Simula

• Simulation programming language from Norway, 1966 (Kristen Nygaard & Ole-Johan Dahl)

• Define an activity which can be instantiated as processes

• Each process has its own data and behavior– In real world, objects don't mess with each others'

internals directly

• (Simulated) Multi-processing– No Universal Scheduler in the Real World

Page 27: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Birth of Objects

• Objects as models of real world entities• Objects as Cells

– Independent, indivisible, interacting -- in standard ways

• Scales well– Complexity: Distributed responsibility, emergent

complexity– Robustness: Independent– Supporting growth: Same mechanism everywhere– Reuse: Provide services, just like in real world

Page 28: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

A Personal Computer for Children

• Flex, an object-oriented personal computer

Page 29: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

FLEX

• Enabled by Moore's Law– Imagining personal computing in 1969

• Logo, Sketchpad, and Simula– Learning representations and knowledge

through programming them– Keyboard and drawing tablet

• Computer as meta-medium– The first medium to encompass other media

Page 30: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Xerox PARC (Palo Alto Research Center)

• Smalltalk-72– Alan Kay, – Dan Ingalls, – Adele Goldberg, – Ted Kaehler

Page 32: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Smalltalk Inventions

• Interface:– overlapping Windows– Icons, even iconic programming– Pop-up menus– Mouse as Pointing device

• Object-oriented programming

• Multimedia authoring environment: Drawing, music, animations

Page 33: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

How Smalltalk was Implemented

• Byte code compiler– Machine language for a make-believe computer

• Virtual machine to create the make-believe computer– Invented years earlier by Burroughs– Used in UCSD Pascal, Java, Python, etc.

• Four files needed for this implementation:– VM– Image file (in byte code)– Sources file (all sources always came along)– Changes file (added sources by user)

Page 34: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Tradeoffs of Virtual Machines

• Advantages:– Can be easily ported

• If VM is well-designed, small amount of code needs to be written for each platform

– The VM can be very small• PowerMac 308K, Win32 328K, Linux-Intel 276K,

SGI Irix 609K, Solaris 816K

• Disadvantages:– Hard to make it efficient

Page 35: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

1981: Xerox releases Smalltalk-80

• In 1981:

Finally Xerox releases Smalltalk-80

Page 36: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Why Smalltalk ?

• Pure object-oriented language• Uniform• Simple• Powerful• Dynamically typed (no type coercion…)• No primitive types• Syntax simple so force to think !!!!!• Discuss design, OO modeling and not

syntax!!

Page 37: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Why Smalltalk ?

• Object Culture

• Environment completely written in Smalltalk

• Powerful development tools

• Good to model real world applications

Page 38: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Part 2

• Structural Organization

• Classes and Subclasses

• Objects and Message Sending

Page 39: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Smalltalk: Interactive & Interpreted

• To satisfy Dynabook’s requirements, it has to be highly interactive. communication with either pointing or typing commands.

• Primary ways of defining things:– Bind a name to an object

X3yx+1

– Class definitionx*2 => send message ‘*2’ to object x

Page 40: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Objects React to Messages

• Smalltalk’s graphical orientation is taken from LOGO.

• LOGO introduced a style of graphics: “turtle graphics”.

Turtle drawing object .

In Smalltalk :pen.

Page 41: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

The position of a pen called

Scribe

Changing position and draw line

Scribe goto: 200@400

Page 42: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Draw another line:Scribe penup.Scribe goto:[email protected] pendn.Scribe goto:500@400.

Go to a specific direction:Scribe go:300

Page 43: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Turn and draw:Scribe turn:90.Scribe go:300.Scribe turn:90.Scribe go:300.

• Control Structures:Scribe penup;goto:400@800;pendn;turn 180.4 timesRepeat:[Scribe go:100. Scribe turn:90]

Page 44: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Important Ideas

1-Objects have a behavior.

2-Objects can be made to do things by sending them messages.

3-Repetitive operations can be simplified by using control structures.

Page 45: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Instantiation

• A class is just a name for a particular kind of object.

• Every object is an instance of some class.

• We have to indicate the class of the instance.

• The process of creating an object is called instantiation.

Page 46: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

• Instantiation is also a message sent to some object.

• Which object should be sent the message ?– A universal system object responsible for all

instantiations– The class relating the object.

• For the sake of Information Hiding Principle: Each class is responsible for its own instantiation.

• anotherScribe pen newAt: 200@800

Page 47: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Class Definition

• To draw another box

- Move the pen

- Instantiate a new pen Violates the Abstraction Principle

• A better solution:

define a class box which can be instantiated any number of times

Page 48: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

• In defining a class, there exists some instance methods and some class methods which describe the behavior of that class. (ex. Instantiation method newAt)

• The instance variable “self”, is implicitly bound to the instance to which it is local.

Page 49: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Example : box class

• Class definition written in tabular form

class name box

instance var names loc tilt size scribe

instance messages and methods

shape || scribe penup; goto: loc; turnTo: tilt; pendn. 4 timesRepeat: [scribe go: size; turn: 90]

erase || scribe color background. self shape

Page 50: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Classes & Subclasses

• Smalltalk objects model real-world objects

• Many of the ideas in Smalltalk derive from Simula.

• Data values inside an object can represent the properties and relations in which that object participates

• The behavior of the Smalltalk object can model the behavior of the corresponding object

Page 51: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Class Group Related Objects

• In the real world, objects are individuals, they differ from one- another

• If all objects were totally different, it would’ve been impossible to understand the world or act effective

Page 52: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Class Group Related Objects

• Objects have many common properties and act similarly.

therefore we abstract these out

• The resulting abstraction, or class, retains the similar properties and omit particulars that distinguishes one individual from another

Page 53: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

• Class definition specifies all of the properties & behaviors common to all instances of the class.

• Instance variable in the object contain the particular information.

• The behavior of the members of the class( messages being responded), is called the protocol of the class (is determined by the instance methods)

Page 54: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

• By modeling some aspects of the real world, we try to find out what would happen under certain conditions

• To do this, laws of cause and effect are needed to describe how certain kinds of objects act in certain situations

in other words: it is necessary to know the relevant behavior of certain classes of objects

• Smalltalk simulates the behavior common to all of the instances of the class

Page 55: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Hierarchical Classification

• When some objects respond to certain common messages:There is Subclass and Superclass

• Subclass inherits the properties and methods of the superclass

• All other classes are are instances( perhaps indirectly) of the class object.

Page 56: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

• Smalltalk applies/violates… principle?– Applies the Abstraction Principle to classes– Violates the Zero-One-Infinity Principle:

allowed only two levels of classes

Page 57: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Behavior : Extended or Modified

• Subclasses allow the behavior of a class to be extended

• Subclasses can build upon the behavior of their superclasses; they can also modify it

• Methods or properties in superclass can be overriden in subclass

• Subclass can still reach the higher level with the word “super”

Page 58: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

overloading is implicit and inexpensive

• Ex. [3+5] the object 3 responds to the message +5 and returns 8

• Ex. [“book” + “keeper” ] the object “book” responds to the message +”keeper” and returns “bookkeeper”

• There is no operator identification problem because the system always knows the class to which an object belongs

Page 59: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Multiple DT Representation

• Classes simplify having several representations for one abstract datatype

Ex. indexStack array

linkStack link list

They work with ‘push’ ‘pop’ ‘empty’• Same protocol (interface) can be used

interchangeably• Thus Smalltalk applies… principles!!

– Information Hiding Principle– Manifest Interface Principle

Page 60: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Self-Displaying Objects

Every displayable object respond to the message print by returning a character string form of itself

Ex. w= 1+2i

z=2+5i

(w+z) print

“3+7i”

Page 61: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Methods accept any object with proper protocol

• It is possible at any time to define a new class and have many existing methods already applicable to it.

• X+Y can work, either integer or polynomial because:

The object x is responsible for responding to the message +y; if x is a number, it does simple addition; if x is polynomial, it does polynomial addition

Page 62: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Operators are handled asymmetrically

– Ex.: let pageNo contain the integer 5.We would expect “page” + pageNo to return the string “page 5”.The + method for strings could accomplish this by sending a message print to the method’s argument( 5).

– Syntactic consistency principlepageNo +”page”

Page 63: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

• For this to take place, the + method of integers should recognize that its second argument is a string, and convert itself to a string.

• What if we extend + to polynomials?

• This situation makes it difficult to take a class( integer) as given and then extend the system by building other classes( e.g.; string ,polynomial)

Page 64: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

• Cause : lack of orthogonality, since the definition of addition should be independent of the integer-to-string coercion.

Page 65: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Hierarchical subclasses preclude orthogonal classification

• In Smalltalk , classes can be immediate subclasses of exactly one other class.

• Trying to arrange the classes in this condition causes:

• Violating Security Principle (one taken from the other)

• Violating Abstraction Principle (repeat data)

Page 66: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Solution?

• There are different sorts of classification in the real-world which are orthogonal

• Multiple Inheritance may be a solution; but:– What is decided a method

or property exists in both superclasses?

– What is decided if something is inherited directly and indirectly?

Page 67: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Everything in Smalltalk is an object

• In Smalltalk, even classes are objects. This design decision satisfies… principles!– Regularity

Page 68: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Simplicity Principle

• A language should be simple as possible, There should be a minimum number of concepts, with simple rules for their combination.

Page 69: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Everything in Smalltalk is an object

• In Smalltalk, even classes are objects. This design decision satisfies… principles!– Regularity– Simplicity

Page 70: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

What are Objects?

• Objects have characteristics of both data (e.g. quantities, properties) and programs( they do things).

• The set of messages to which an object can respond is called its protocol

• When an object is sent a message, the Smalltalk system produces an error diagnostic if that message is not part of the object’s protocol.

• Objects are instantiated dynamically

Page 71: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Names Are Not Typed

• Variables in Smalltalk don’t have type!

• Why is this good?– Polymorphism!

Circle Triangle RectangleSquare

Shapesshape1 draw.shape2 draw.shape3 draw.

Page 72: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Names Are Not Typed

• What about type checking?– Type checking occurs when a message is

sent to the object bound to a name. If the object responds to that message(i.e. the message is in its protocol), then the message is legal; otherwise it is not.

• Smalltalk like LISP, has strong, but dynamic, typing.

Page 73: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

• Does Smalltalk’s dynamic type checking violate the Security Principle?– No! Smalltalk system will allow a message to

be sent to an object only if that object has a method to respond to the message.

Page 74: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Error Detection

• Instead of machine-code, Smalltalk has all of the source code available at run-time.

• In case of an error, Smalltalk can produce run-time diagnostics.

• A run-time error causes the program to be suspended. An offending class can be edited and quickly recompiled and the execution of the program can be resumed

Page 75: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Storage Utilization

• Every object is accessed through an object reference, that is, a pointer. Therefore all variables and parameters occupy the same amount of storage-one pointer.

Page 76: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Documentation

• The designers of Smalltalk claim that well-named variables provide just as good documentation.

• For E.g. calling a parameter anInteger makes its intended value just as clear as a typed declaration like n: integer

Page 77: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Dynamic Typing & Flexibility

• Any object with the proper protocol can be passed to a method.

• A major application of Abstraction Principle: common algorithms can be factored out of a system without complicated mechanisms.

Page 78: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Three Kinds of Message Syntax

• Parameterless messages– B1 show

• Unary messages– x+y

• Messages with one or more parameters– Scribe grow:100

• Satisfies the… Principle.– Zero-One-Infinity

Page 79: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

The Smalltalk Main Loop is Written in Smalltalk

• Like most interactive systems, Smalltalk is in a loop: Read a command, execute the command, print the results, and loop:– True whileTrue: [Display put: user run]

• Variable user contains an object called user task containing:– … run ||

• Keyboard read eval print

Page 80: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

• Strings respond to the message eval by calling the Smalltalk compiler and interpreter to evaluate themselves.

Page 81: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Concurrency is Easy to Implement

• Concurrent programming can be done by having the main loop run each of a set of tasks.

• This can be done by applying “run” to every element of the set S with S: map run

• A task T can be run (terminated) by adding (deleting) it to (from) the set S– S add : T

Page 82: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

• To implement different scheduling algorithms, one should keep the objects in ordered lists and reorder the list according to some priority system.

Page 83: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Part 3

• Object Representation• Class Representation• Activate Record

Representation• Message

– Sending – Returning

Page 84: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Implementation

• Portability– More of the Smalltalk system is written in

Smalltalk– Compiler, decompiler, debugger, editor, file

system– 97% of the code– Smalltalk objects

Page 85: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

• Smalltalk-80 virtual machine– Not portable– Between 6 and 12 kilobytes– Require one man-year to produce fully

debugged version

• Three major components– Storage Manager– Interpreter– Primitive Subroutines

Implementation

Page 86: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Storage Manager

• Abstract data type manager for objects• Information Hiding Principle• Operations provided for other modules for

manipulating objects– Fetch the class of an object– Fetch and Store the fields of objects– Create new objects

• Managing Free Space– Reference Counting with extension for cyclic

structures

Page 87: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Interpreter

• Heart of the Smalltalk system

• Interpret Smalltalk written form or

intermediate form ( more efficient )

• Abstract data type manager for methods

Page 88: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Primitive Subroutines

• Collection of methods that, for performance reasons, are implemented in machine code

• Basic Input-Output functions, integer arithmetic, basic screen graphics operations, …

Page 89: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Three Central Ideas in Smalltalk

• Objects

• Classes

• Message sending

Page 90: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Objects Representation

• Abstraction and Information Hiding Principles

• Just information that varies from object to object ( instance variables )

• A pointer to the data structure representing the class

Page 91: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Objects Representation

Box

6len.

loc

tilt

size

scribe

c.d.len.

c.d.

y

x

Point

500

200

4

Page 92: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Class Representation

• Every thing is an object without exception

(Regularity Principle)

• An object of a class named “class”

• Information for representing– Class name– Super class name– Instance variable names– Class message dictionary– Instance message dictionary

Page 93: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Class Representation

len

c.d.

name

super class

class msgs.

inst. msgs

inst. size

inst. vars

8 class

“box”

displayObject

“loc tilt size scribe”

message dict.

message dict.

4

class

string

class

string

messageDictionary

messageDictionary

Page 94: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Message Dictionary

• Message template

• Example– Scribe go: 100

message template is “go:”– Spinner newAt: 500@200 rate: 1

message template is “newAt:rate:”

• “go:”, “newAt:”, “rate:” are keyword

Page 95: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Message Dictionary

• Finding the message template in message dictionary by using hashing techniques

• Contains two entry for each message template– Source form

• For editing and displaying class definitions

– Compiled form• For rapidly interpreting

Page 96: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Message Dictionary

msg sourcemethod

“grow:”

“grow: amount | | self erase.size ← size + amount. self show”

push ‘self’…

returnstring

string

method

messageDictionary

Page 97: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Message Sending Representation

• String resemblance between message sending in Smalltalk and procedure calls in other languages

• Very similar implementation techniques

• Activation Record

• Some important differences

Page 98: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Activation Record Structure

• Sender Part– A dynamic link to the sender’s activation

record ( just a pointer )

• Instruction Part– Object pointer– Relative offset– Goes throw the storage manager

( Information Hiding Principle )

Page 99: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Activation Record Structure

• Environment Part– Local environment

• Parameters• Temporary variables• Intermediate results• Example

– newAt: initialLocation | newBox |

newBox ← box new.

initialLocation

newBox

intermediate results

Page 100: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Activation Record Structure

– Non-local environment• All other visible variables• Namely instance variables and class variables• A simple pointer to that object, static link

Page 101: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Activation Record Structure

Page 102: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Message Sending and Returning

• When a message is sent to an object– Create callee’s activation record– Identify the method by looking in the

message dictionary for that class or its super class or ….

– Transmit the parameters– Suspend the sender and saving its state in its

activation record– Establish the dynamic link and activate

receiver’s activation record

Page 103: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Message Sending and Returning

• Returning from the method– Transmit the returned object ( if any ) back to the

sender– Resume execution of sender

• Why omitting the deallocation of the receiver’s activation record?

• Storage manager• Information Hiding Principle• Not in the stack• Less efficient, but more simple and regular

Page 104: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Message Sending and Returning

• Another reason, concurrency

• The scheduler must wait for each task to return from its run method, an important limitation

• Real Smalltalk systems provide interrupt facility

• Time sharing

Page 105: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Message Sending and Returning

• What does happen if we use stack?

• Consider this example

• Two possibilities:– Popping N and M– Popping M from middle

of the stack

• No one is correct

• Stack is appropriate for LIFO discipline

N

M

Page 106: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Part 4

• Smalltalk Terminology• Comparison with other

OO languages• Syntax Overview• Conclusions

Page 107: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Smalltalk Language Terminology

• Object Instance of some class

• Class Defines behavior of its objects

• Selector Name of a message

• Message Selector together with parameter values

• Method Code used by a class to respond to message

• Instance variable Data stored in object

• Subclass Class defined by giving incremental modifications to some super class

Page 108: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Smalltalk vs. C++ and Java ?

Smalltalk • “Everything is an object” • Objects are passed by reference • Objects are the units of encapsulation

C++ • “Everything is a structure” • Objects are passed by value (pointers) • Classes are the units of encapsulation

Java • “Almost everything is an object” • Objects are passed by reference (no pointers) • Classes are the units of encapsulation (like C+

+)

Page 109: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Syntax Differences

• Languages: C++ / Java Smalltalk

Comments/*comments*///comments

“comment”

Assignments int max=100; Variable := value

Basic Types “string” ‘string’

Self Reference thisthis.getClass()

selfself class

Page 110: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

C++ compared to Smalltalk

• C++ is…– Mixed paradigm programming: objects, but can have functions,

too– Compiled to native code (Recall: main goal is efficiency)– Based on traditional functions and stack-based scoping– Strongly typed– Storage is controlled by the programmer

• Smalltalk is…– Dynamic (feels like an interpreter)– Byte-code compiled– Persistent objects– Not at all typed– Garbage collection: storage is managed by the system

Page 111: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Java compared to the others

• Java looks like C++, but…– Mostly objects (no functions, but some

primitive types)– Uses a VM– Objects are more like C++'s than Smalltalk’s– Even more strongly typed– Storage is handled by garbage collection

Page 112: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Encapsulation (Smalltalk vs. C++)

In C++:

• not everything is an object

• pseudo message passing through member functions

• not all of an object’s state is encapsulated– public data variables– keyword ‘friend’

Page 113: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Encapsulation (Smalltalk vs. C++)

dataPrivateData

Methods

variablesother objectsPublic Data

“Friend”

Page 114: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Inheritance (Smalltalk vs. C++)

In Smalltalk:

• Generalization & Specialization

• Subclass & superclass

• Every class has a superclass

Animal

Bird MammalReptile

DogHorseSnake

Page 115: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Inheritance (Smalltalk vs. C++)

In Smalltalk:

ACCOUNTbalance

withdrawdeposit

SAVINGSrate

setRateapplyInterest

Super class

Subclass

Page 116: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Inheritance (Smalltalk vs. C++)

In Smalltalk:

• How does it support our objectives?– Models real world

• group similar ‘things’ into class hierarchy

– Reusability & Ease of use• create new classes by specializing existing ones

Page 117: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Inheritance (Smalltalk vs. C++)

• Inheritance in C++– public, private, protected– burden on programmer

• Multiple Inheritance– Supported in C++– Not supported in Smalltalk

Class Amethod:

print

Class ABprint??

Class Bmethod:

print

Page 118: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Free Implementations

• Squeak (Smalltalk for Win , Mac, etc.)– http://www.squeak.org/download/index.html

• GNU Smalltalk (Unix systems only) – http://www.gnu.org/software/smalltalk/smalltalk.html

Page 119: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Squeak Desktop

Page 120: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Hello World Example

Page 121: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Squeak → Pros and Cons

• Pros– Developed by the inventors of Smalltalk– Open source– Fun– Multimedia, 3D, Sounds,….

• Cons– You may think that Smalltalk is not serious– Code is sometimes not so good

Page 122: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Syntax (1 of 12) → Literals

• numbers -45.3, 1.5e3, 8r377

• characters $a, $-, $$

• strings ‘hello’, ‘won’’t’

• symbols (names) #M63, #bill

• arrays of other literals #(1 2 3), #( ‘who’ $q (1 2) -1)

Page 123: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Syntax (2 of 12) → Pseudo Variables

Pseudo-Variables:

– true, false, nil “constants”– self, super “relative to situation”

Page 124: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Syntax (3 of 12) → Assignment

default <- 100

“default refers to same object as 100”

list <- #(1 2 ‘three’ $4)

“list will be an array of objects 1,2,’three’, $4”

Page 125: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Syntax (4 of 12) → Messages

• receiver + selector(s) [+ arguments]• three forms

– unary – receiver plus one selector onlye.g., stack top, 90 sin

– binary – receiver plus selector plus argumente.g., stack push $q, 12 / 5

– keyword – receiver plus keyword argument pairse.g., arrayList at: 10 put: ‘junk’(selector is at:put:)

• precedence: unary, binary, keyword• associativity: left to right

Page 126: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Syntax (5 of 12) → Control Structures

• simple repetition

4 timesRepeat: [ amt <- amt + 1 ]

• conditional repetition

i <- 1

[i <= list size]

whileTrue: [list at: i put: 0.

i <- i + 1 ]

Page 127: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Syntax (6 of 12) → Control Structures

• selection

number = 0

ifTrue: [ parity <- 0]

ifFalse: [ parity <- 1]

i <= limit

ifTrue: [tot <- tot + list at:i]

Page 128: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Syntax (7 of 12)

• 1 + 2

Here 1 is an instance of class Integer, + is the message and 2 its argument. Both + and 2 are objects as well.

• 2 + 3 * 5

2 + 3 evaluates to an Integer object. Then it is sent message * and 5 as an argument.

Page 129: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Syntax (8 of 12)

• x = 0 ifTrue: [ ... ]

Message = is sent to object x with the argument 0. The resulting object (Boolean) is sent message ifTrue with a code block as an argument.

If x = 0 doesn’t evaluate to Boolean, the error will be detected at run time.

Page 130: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Syntax (9 of 12)

• [ ... ] whileTrue: (expr)

The block object is sent message whileTrue with an expression as an argument.

• MyClass new initialize: 0

Creates an instance of MyClass and calls its ”constructor” with an argument 0.

Page 131: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Syntax (10 of 12)

• | i | ...

Declares variable i.

• | i | i := Integer new: 5

Assignment to i.

• | :p | ...

Declares p as a parameter variable.

Page 132: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Syntax (11 of 12)

• #foo

Refers to symbol foo.

• #(5 8 29 10)

Declares an Array object that holds Integers 5, 8, 29 and 10.

Page 133: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Syntax (12 of 12)

• Classes are defined by using the graphical programming environment.

• Methods and variables (not the local ones) are also declared this way.

Page 134: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Costs and benefits of “true OO”

• Why is property of Ingalls test useful?– Everything is an object– All objects are accessed only through interface– Makes programs extensible

• What is implementation cost?– Every integer operation involves method call

• Unless optimizing compiler can recognize many cases

– Is this worth it?• One application where it seems useful ?• One application where it seems too costly?• Are there other issues? Security? (wait for Java final

classes…)

Page 135: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Advantages

Encapsulation Inheritance Dynamic Binding Storage Management

Models Real World

Reusability

Ease of use

Page 136: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

Smalltalk Summary

• Class– creates objects that share methods– pointers to template, dictionary, parent class

• Objects: created by a class, contains instance variables

• Encapsulation – methods public, instance variables hidden

• Sub typing: implicit, no static type system

• Inheritance: subclasses, self, super Single inheritance in Smalltalk-76, Smalltalk-80

Page 137: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

To Learn More About Smalltalk

• Lectures on Smalltalk– www.iam.unibe.ch/~ducasse/

• Lectures of Ralph Johnson– www.cs.uiuc.edu/users/cs497/lectures.html– Yes one of the Gang of Four Book (Design

Patterns) is a Smalltalk Guru!!

• Lectures of Roger Withney– http://www.eli.sdsu.edu/courses/spring01/

cs635/index.html

Page 138: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

To Learn More About Smalltalk

Local Websitehttp://www.iam.unibe.ch/~scg/Resources/Smalltalk/

http://www.iam.unibe.ch/~ducasse/PubHTML/Smalltalk.htmlLocal Wiki: http://scgwiki.iam.unibe.ch:8080/SmalltalkWiki/Cincom Smalltalk http://www.cincom.com/smalltalk/Squeak http://www.squeak.org/

http://www.cc.gatech.edu/squeak.1Dolphin Smalltalk http://www.object-arts.com/Home.htm

http://www.smalltalk.orghttp://www.goodstart.com/index.shtmlhttp://st-www.cs.uiuc.edu/

VisualWorks Wiki http://brain.cs.uiuc.edu/VisualWorks/VisualAge Wiki: http://brain.cs.uiuc.edu/VisualAge/Newsgroup: comp.lang.smalltalkESUG http://www.esug.org/BSUG http://www.bsug.org/GSUG http://www.gsug.org/SSUG http://www.iam.unibe.ch/~ssug/

Page 139: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

To Learn More About Smalltalk

• Smalltalk Books:• Smalltalk by Example, Alec Sharp

– Pdf at: http://www.iam.unibe.ch/~ducasse/WebPages/FreeBooks.html

• Best Smalltalk Pratices, K. Beck

• Smalltalk Pattern Design Companion, S.Alpert, K.Brown and B.Woolf

• Squeak, X. Briffault, S. Ducasse (fr)

Page 140: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

To Learn More About Smalltalk

• Books for Starting:• On To Smalltalk, P. Winston, Addison-Wesley, 1998, 0-

201-49827-8 • Smalltalk by Example : The Developer's Guide, A.

Sharp, McGraw Hill, ISBN: 0079130364, 1997• http://www.iam.unibe.ch/~ducasse/FreeBooks.html• Smalltalk: an Introduction to application development

using VisualWorks, T. Hopkins and B. Horan, Prentice-Hall,1995, 0-13-318387-4

• Joy of Smalltalk, Ivan Tomek• http://brain.cs.uiuc.edu/VisualWorks/Joy+of+Smalltalk• Chamond, Liu, Smalltalk, Objects, and Design,

iUniverse.com, ISBN: 1583484906, 2000.

Page 141: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

To Learn More About Smalltalk

• Advanced References• Smalltalk Best Practice Patterns, K. Beck, Prentice Hall,

1997, ISBN 0-13-476904-x• The Design Patterns Smalltalk Companion, S. Alpert and

K. Brown and B. Woolf, Addison-Wesley, 1998,0-201-18462-1

• Smalltalk with Style, S. Skublics and E. Klimas and D. Thomas, Prentice-Hall, 1996, 0-13-165549-3.

• The Smalltalk Developer’s Guide to VisualWorks, T. Howard, Sigs Books, 1995, 1-884842-11-9

• Mastering Envy/Developer, A. Knight, J. Pelrine, and A Chou., SIG Press.

Page 142: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

…..Thanks for listening…..

…..Any Question ?…..

Page 143: An Introduction to Smalltalk First Pure Object Oriented Language By: Misagh Bagherian

• We hope by this time you’ve been learned important concepts of OOP and Smalltalk as the first (and maybe only) pure OO language !