Introduction to Smalltalk

Slides:



Advertisements
Similar presentations
11. A bit of Smalltalk. © O. Nierstrasz P2 — A bit of Smalltalk 11.2 A bit of Smalltalk Overview  Some history  Smalltalk syntax & object model  The.
Advertisements

Principles of Object-Oriented Software Development The language Smalltalk.
Road Map Introduction to object oriented programming. Classes
Stéphane Ducasse 1 The Taste of Smalltalk.
13. A bit of Smalltalk. © Oscar Nierstrasz 2 Roadmap  The origins of Smalltalk  What is Smalltalk?  Syntax in a nutshell  Seaside — web development.
PZ06BX Programming Language design and Implementation -4th Edition Copyright©Prentice Hall, PZ06BX - Introduction to Smalltalk Programming Language.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 13 Object-Oriented Programming I am surprised.
Squeak Collections The Squeak collection hierarchy. Some collection operators. Working with collections. For-loops.
Object-oriented programming and design 1 Smalltalk in a Nutshell Objects & classes Messages & methods Inheritance & metaclasses.
Stéphane Ducasse5.1 Smalltalk in a Nutshell OO Model in a Nutshell Syntax in a Nutshell.
12. A bit of Smalltalk. © O. Nierstrasz P2 — A bit of Smalltalk 11.2 Roadmap  Some history  Smalltalk syntax & object model  The Smalltalk environment.
Stéphane Ducasse 1 Smalltalk in a Nutshell.
S.Ducasse Stéphane Ducasse 1 The Taste of Smalltalk.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
CS 598 Scripting Languages Design and Implementation 7. Smalltalk 80.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
Smalltalk (and Squeak) Aida Dungan and Rick Shreve.
Chapter 12 Support for Object oriented Programming.
Squeak and Botkit-Port Jeff Forbes Joel Miller. Introduction ● Squeak is a pure OO language ● Based off of SmallTalk-80 – Designed at Xerox PARC by Alan.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
VARIABLES, CONSTANTS, OPERATORS ANS EXPRESSION
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
3C-1 Identifiers Variables Literal Objects  Numbers  Characters  Strings Control Structure  Blocks  Conditionals  Loops Messages Defining New Classes.
1 Program Development  The creation of software involves four basic activities: establishing the requirements creating a design implementing the code.
S.Ducasse Stéphane Ducasse 1 Smalltalk in a Nutshell.
S.Ducasse Stéphane Ducasse savoie.fr e/ e/ 1 Smalltalk in a Nutshell.
CSE 3302 Programming Languages Chengkai Li Fall 2007 Smalltalk Lecture 14 – Smalltalk, Fall CSE3302 Programming Languages, UT-Arlington ©Chengkai.
Introduction to Objects and Encapsulation Computer Science 4 Mr. Gerb Reference: Objective: Understand Encapsulation and abstract data types.
Stéphane Ducasse 1 A Little Journey in the Smalltalk Syntax.
Administrative Issues Lecture 22 – Prolog (III), Fall 2007 CSE3302 Programming Languages, UT-Arlington ©Chengkai Li, HW3 (due at March 18 th ) Essay.
Chapter 1.2 Introduction to C++ Programming
Definition of the Programming Language CPRL
Ruby: An Introduction Created by Yukihiro Matsumoto in 1993 (named after his birthstone) Pure OO language (even the number 1 is an instance of a class)
7.1 What Is An Object Object-oriented program - Description or simulation of application Object-oriented programming is done by adopting or extending an.
CMSC201 Computer Science I for Majors Lecture 22 – Binary (and More)
Building Java Programs
Introduction to Computer Science / Procedural – 67130
Class 22: Inheritance CS150: Computer Science University of Virginia
Java Primer 1: Types, Classes and Operators
Multiple variables can be created in one declaration
Primitive Data, Variables, Loops (Maybe)
The Selection Structure
Programming Language Concepts (CIS 635)
Arrays, For loop While loop Do while loop
Building Java Programs Chapter 2
Type Conversion, Constants, and the String Object
Feedback from Assignment 1
Smalltalk – a Pure (and first) OOPL
Introduction to C++ Programming
Introduction to Java part 2
Building Java Programs
C++ Data Types Data Type
Chapter 2 Squeak: Object-oriented design with multimedia applications
Building Java Programs Chapter 2
Python Primer 1: Types and Operators
Chapter 3: Selection Structures: Making Decisions
Building Java Programs
Introduction to Java part 2
Fundamental OOP Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Building Java Programs
In this class, we will cover:
Introduction to Programming
Unit 3: Variables in Java
Building Java Programs Chapter 2
Let’s Talk about… Smalltalk.
Introduction to Smalltalk
Building Java Programs
CSE 3302 Programming Languages
Smalltalk on a Dime.
Presentation transcript:

Introduction to Smalltalk The Design of Smalltalk & Understanding Code Introduction to Smalltalk

Sample Code (Integer) factorial “Returns the factorial of this integer. ‘5 factorial’ evaluates to 120.” self < 0 ifTrue: [^self error: ‘Not defined’]. self = 0 ifTrue: [^1]. ^self * (self - 1) factorial Here is a sample code for the instance method factorial on the Integer class. Integer is shown in gray, because you don’t write it. You determine which class is associated with the method through the interface (the Browser). Introduction to Smalltalk

Sample Code The Method Name (Integer) factorial “Returns the factorial of this integer. ‘5 factorial’ evaluates to 120.” self < 0 ifTrue: [^self error: ‘Not defined’]. self = 0 ifTrue: [^1]. ^self * (self - 1) factorial The Method Name Introduction to Smalltalk

Sample Code A Comment (Integer) factorial “Returns the factorial of this integer. ‘5 factorial’ evaluates to 120.” self < 0 ifTrue: [^self error: ‘Not defined’]. self = 0 ifTrue: [^1]. ^self * (self - 1) factorial A Comment Introduction to Smalltalk

Sample Code A String (Integer) factorial “Returns the factorial of this integer. ‘5 factorial’ evaluates to 120.” self < 0 ifTrue: [^self error: ‘Not defined’]. self = 0 ifTrue: [^1]. ^self * (self - 1) factorial A String Introduction to Smalltalk

Sample Code Referring to the object itself (Integer) factorial “Returns the factorial of this integer. ‘5 factorial’ evaluates to 120.” self < 0 ifTrue: [^self error: ‘Not defined’]. self = 0 ifTrue: [^1]. ^self * (self - 1) factorial Referring to the object itself Introduction to Smalltalk

Sample Code Periods separate statements (can skip on last line) (Integer) factorial “Returns the factorial of this integer. ‘5 factorial’ evaluates to 120.” self < 0 ifTrue: [^self error: ‘Not defined’]. self = 0 ifTrue: [^1]. ^self * (self - 1) factorial Periods separate statements (can skip on last line) Spaces, besides separating tokens, mean nothing. Introduction to Smalltalk

Sample Code Return the value from the method (Integer) factorial “Returns the factorial of this integer. ‘5 factorial’ evaluates to 120.” self < 0 ifTrue: [^self error: ‘Not defined’]. self = 0 ifTrue: [^1]. ^self * (self - 1) factorial Return the value from the method Introduction to Smalltalk

Sample Code Blocks (Integer) factorial “Returns the factorial of this integer. ‘5 factorial’ evaluates to 120.” self < 0 ifTrue: [^self error: ‘Not defined’]. self = 0 ifTrue: [^1]. ^self * (self - 1) factorial Blocks Smalltalk blocks are closures. They combine a piece of code with a lexical environment. Introduction to Smalltalk

The Design of Smalltalk Smalltalk is really simple It was meant to be In its simplicity lies its greatness “We aim to make simple things simple and complex things possible.” —Alan Kay Foundations of Smalltalk Everything is an object Class-based inheritance All computation is done through message passing Modeled on English (e.g., periods end statements) Back in the 70s, Alan Kay at Xerox PARC was working on a programming language for children. At a party, he was discussing the link between natural language and programming languages. Back then, there were many systems around with impressive sounding names, like Oberon and Thor. Unfortunately, these systems weren’t very good. Kay expressed his dissatisfaction with an analogy: “I hope at some point programming languages rise to the level of small talk (AKA chit chat).” It was an oddly appropriate name for a language designed for children. As a side note, Smalltalk never worked well with children. OO programming is just too difficult. It worked really well for professional programmers though. Introduction to Smalltalk

Everything is an Object There are no exceptions. Numbers, Booleans, etc. nil is an object (it is the only instance of ProtoObject, the root of the class inheritance tree) Even every class is an object Blocks and methods are objects too Introduction to Smalltalk

Class-Based Inheritance Smalltalk is the Canonical Class-Based Object-Oriented Language Every object is an instance of some class All classes (except ProtoObject) have a parent class Parent is superclass Child is subclass Subclasses inherit behavior and structure from parent class Introduction to Smalltalk

Class Hierarchy: SmallInteger Magnitude Character Date Number Float Fraction Integer SmallInteger LargePositiveInteger LargeNegativeInteger Time Introduction to Smalltalk

Class Hierarchy: Collections SequencableCollection ArrayedCollection Array String (‘I am a String’) Symbol (#IAmASymbol) OrderedCollection (like a resizable Array) SortedCollection Set (keeps unique values only) Dictionary (like a hash table) Introduction to Smalltalk

Message Passing All computation is triggered through message sends (sending a message to an object) Messages trigger methods Almost all of Smalltalk is <receiverObject> <message> 5 factorial 5 is the receiver object, factorial is the message 5 + 3 5 is the receiver object, + is the message, 3 is an argument How do we get from the message to the method? Introduction to Smalltalk

Message Passing Answer: Through the Class Hierarchy 5 factorial 5 + 3 Class determines behavior. Check the class of the receiver object for the method. If not found, check the parent. Go through the class hierarchy until found or return a “does not understand” error. 5 factorial 5 is a SmallInteger. It’s parent (Integer) implements factorial. 5 + 3 5 is a SmallInteger, which implements + Introduction to Smalltalk

Message Passing There can be more than one method implementing the same message Which method gets executed is based on the class of the receiver Methods in Object (like printString) can be sent to any object The decision is made at runtime This is late-binding More than one kind of object can respond to the same message in its own way 5 + 3 and 5.1 + 3.2 are very different methods This is polymorphism Polymorphism allows you to program in terms of goals not code. Introduction to Smalltalk

Message Passing All computation is triggered through message passing Even control structures are handled as message sends Introduction to Smalltalk

Control Structures test ifTrue: [“Execute if test is true”] 1 to: 10 do: [:i | “Iterate for i equals 1 to 10”] [test] whileTrue: [“Repeat this until test is false”] Introduction to Smalltalk

Control Structures Receiver Message (ifTrue: to:do: whileTrue:) test ifTrue: [“Execute if test is true”] 1 to: 10 do: [:i | “Iterate for i equals 1 to 10”] [test] whileTrue: [“Repeat this until test is false”] Receiver Message (ifTrue: to:do: whileTrue:) Argument(s) Introduction to Smalltalk

Control Structures test ifTrue: [“Execute if test is true”] 1 to: 10 do: [:i | “Iterate for i equals 1 to 10”] [test] whileTrue: [“Repeat this until test is false”] Remember, everything is an object. Even blocks are objects Boolean, False, and True implement ifTrue: Number implements to:do: BlockContext implements whileTrue: Introduction to Smalltalk

Sample Code Receiver Message Argument (Integer) factorial “Returns the factorial of this integer. ‘5 factorial’ evaluates to 120.” self < 0 ifTrue: [^self error: ‘Not defined’]. self = 0 ifTrue: [^1]. ^self * (self - 1) factorial Receiver Message Argument Introduction to Smalltalk

Compiler and Blocks Compiler in always available Compiler evaluate: ‘3 + 4’ “returns 7” Blocks: Code elements that are objects aBlock := [Smalltalk beep]. “blocks can be assigned to variables” aBlock value. “do it” Blocks can take arguments asArgumentBlock := [:x | x+1]. anArgumentBlock value: 5. “returns 6” Introduction to Smalltalk

3 timesRepeat: [Smalltalk beep] (Integer) timesRepeat: aBlock “Evaluate the argument, aBlock, the number of times represented by the receiver.” | count | count := 1. [count <= self] “test for while” whileTrue: [ aBlock value. “evaluate block” count := count + 1] “increment count” Introduction to Smalltalk

Message Passing Message Names are Objects (Symbols) #factorial #to:do: #whileTrue: #+ You can use them like any other object (save them to a variable, etc.) The following evaluate the same 5 factorial 5 perform: #factorial 5 perform: #perform: with: #factorial Eventually, we’ll see how useful that is for building user interfaces. Introduction to Smalltalk

Kinds of Operators (Ways to Send Messages) Binary + - * / // “quotient” \\ “remainder” | & “do not short-circuit” Unary abs not sin positive asUppercase Keywords with : aDictionary at: aKey put: aValue to:do: ifTrue:ifFalse: Order of precedence (not algebraic) (First to Last) Parenthesis, Unary, Binary, Keyword First come: First served Introduction to Smalltalk

Sample Code Unary Operators (Integer) factorial “Returns the factorial of this integer. ‘5 factorial’ evaluates to 120.” self < 0 ifTrue: [^self error: ‘Not defined’]. self = 0 ifTrue: [^1]. ^self * (self - 1) factorial Unary Operators Introduction to Smalltalk

Sample Code Binary Operators (Integer) factorial “Returns the factorial of this integer. ‘5 factorial’ evaluates to 120.” self < 0 ifTrue: [^self error: ‘Not defined’]. self = 0 ifTrue: [^1]. ^self * (self - 1) factorial Binary Operators Introduction to Smalltalk

Sample Code Keyword Selectors (Integer) factorial “Returns the factorial of this integer. ‘5 factorial’ evaluates to 120.” self < 0 ifTrue: [^self error: ‘Not defined’]. self = 0 ifTrue: [^1]. ^self * (self - 1) factorial Keyword Selectors Introduction to Smalltalk

Sample Code Figure out the precedent (Integer) factorial “Returns the factorial of this integer. ‘5 factorial’ evaluates to 120.” self < 0 ifTrue: [^self error: ‘Not defined’]. self = 0 ifTrue: [^1]. ^self * (self - 1) factorial Figure out the precedent Introduction to Smalltalk

Sample Code 1st Parenthesis (Integer) factorial “Returns the factorial of this integer. ‘5 factorial’ evaluates to 120.” self < 0 ifTrue: [^self error: ‘Not defined’]. self = 0 ifTrue: [^1]. ^self * (self - 1) factorial 1st Parenthesis Introduction to Smalltalk

Sample Code 2nd Unary (Receiver) (Integer) factorial “Returns the factorial of this integer. ‘5 factorial’ evaluates to 120.” self < 0 ifTrue: [^self error: ‘Not defined’]. self = 0 ifTrue: [^1]. ^self * (self - 1) factorial 2nd Unary (Receiver) Introduction to Smalltalk

Sample Code 3rd Binary (Receiver) (Argument) (Integer) factorial “Returns the factorial of this integer. ‘5 factorial’ evaluates to 120.” self < 0 ifTrue: [^self error: ‘Not defined’]. self = 0 ifTrue: [^1]. ^self * (self - 1) factorial 3rd Binary (Receiver) (Argument) Introduction to Smalltalk

Class-Based Inheritance Instances and classes do not respond to the same messages (Java and Smalltalk differ here) In Java, instances will respond to class (static) methods. In Smalltalk, they are separate. The class responds to a message with class methods. The instances respond to a message with instance methods. In general, the Smalltalk separation is better for good object-oriented programming style. A class and its instance aren’t the same type of object; therefore, they shouldn’t share methods. Consider rover := Dog new. rover name: ‘Rover’. brody := rover new. “Does that make sense?” brody := rover class new. “That’s better.” Introduction to Smalltalk

Class-Based Inheritance Classes are instances too Each class has its own metaclass The class is an instance of that metaclass Because of this, all class methods are actually instance methods Again, Smalltalk is simple: There is only one kind of method (instance methods) Introduction to Smalltalk

Class-Based Inheritance Accessing an Object All instance variables are private You can’t just reach in and manipulate an object. Good OO Programming: “Ask. Don’t Touch.” You can use simple accessors and mutators when appropriate to simulate public variables All methods are public If a object implements a message, you can send that message to the object and it will try to do it. This can lead to errors, but Smalltalk deals with errors fairly well. You will occasionally see comments or category names warning that a message is really private. Introduction to Smalltalk

Modifying Classes and Methods Trust the Programmer In Smalltalk, you can modify any class or method. You can create new methods on any class. So, if you need to add a factorial capability, add it as a method to the Integer class. That’s where it belongs. Consider the following: FactorialProcessor factorialFor: 5 “not good OO code: Make the object do the work.” 5 factorial 5.0 factorial “returns an error.” Introduction to Smalltalk

Creating a New Class: Use the SystemBrowser Object subclass: #NameOfClass instanceVariableNames: ‘instVarName1 instVarName2’ classVariableNames: ‘ClassVarName1 ClassVarName2’ poolDictionaries: ‘’ category: ‘Kernel-Numbers’ Notes ParentClass NewClass Smalltalk is case sensitive Classes start with uppercase # is significant: Class names are Symbols Wipe out the things you don’t want, but leave the quotes ‘’ Ignore poolDictionaries We’ll talk more about the SystemBrowser when we get going in Squeak. Introduction to Smalltalk

Variables Variables: Any word starting with a letter | foo bar | “Local Variables” foo := 1. “Assignment” foo  ‘one’. “underscore is same as :=“ Variables: Any word starting with a letter Start with lowercase, unless it is global You don’t declare variable type All variables have a type (class of the object they point to) Variables start as nil (type = ProtoObject) The code above works fine. After line 2, foo is a SmallInteger (1). After line 2, foo is a String (one). Introduction to Smalltalk

Variables Variables point to objects Objects with no references are garbage collected You can have multiple variables point to the same object a := #(1 2 3). “An Array with 1, 2, and 3” b := a. a at: 2 put: 75. ^b “Returns #(1 75 3)” Making copies: copy vs. deepCopy Checking for sameness = equality “objects have the same value” == equivalence “same object” copy vs. deepCopy - do you copy the instance variables of an object as well? Introduction to Smalltalk

Collections: Choosing a Collection Class Array (fixed size, ordered) OrderedCollection (like Array, but can grow in size) SortedCollection (OrderedCollection, but sorted according to block) Dictionary (hash table) Set (unordered, no redundancies) Bag (count the number of pieces) The grayed out ones are less useful. An OrderedCollection does everything that an Array can do and it is more flexible. Introduction to Smalltalk

Collections Adding and removing elements Testing Enumerating add: addAll: remove: removeAll: Testing isEmpty includes: occurencesOf: Enumerating ‘squeak’ do: [:char | Transcript show: char printString] ‘squeak’ select: [:char | char isVowel] ‘uea’ #(4 1 6) reject: [:num | num even] #(1) #(4 1 6) select: [:num | num odd] #(1) #(4 1 6) collect: [:num | num factorial] #(24 1 720) String is just a specific type of ArrayedCollection. Introduction to Smalltalk

Dictionaries Has Key/Value pairs (like a hash table) a := Dictionary new. a at: ‘orange’ put: ‘orange’. a at: ‘apple’ put: ‘red’. a at: 5 put: 678. a keys. #(‘orange’ 5 ‘apple’) a values. #(678 ‘orange’ ‘red’) a at: ‘orange’. ‘orange’ a keysAndValuesDo: [:key :value | “enumerating”] Dictionaries are unordered, so you may not get the keys back in the order you put them in. Introduction to Smalltalk

Odds and Ends Characters String concatenation (comma) Examples: $1 $a $. String is a collection of Characters String concatenation (comma) ‘peanut butter’, ‘ and ‘, ‘jelly’ ‘peanut butter and jelly’ Cascade (semicolon) Sending multiple messages to the same object Dog new name: ‘Rover’; breed: ‘Mutt’; owner: me. Introduction to Smalltalk