Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Smalltalk

Similar presentations


Presentation on theme: "Introduction to Smalltalk"— Presentation transcript:

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

2 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

3 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

4 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

5 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

6 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

7 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

8 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

9 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

10 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

11 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

12 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

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

14 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

15 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

16 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

17 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 are very different methods This is polymorphism Polymorphism allows you to program in terms of goals not code. Introduction to Smalltalk

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

19 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

20 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

21 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

22 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

23 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

24 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

25 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

26 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

27 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

28 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

29 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

30 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

31 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

32 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

33 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

34 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

35 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

36 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

37 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

38 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

39 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

40 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

41 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

42 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] #( ) String is just a specific type of ArrayedCollection. Introduction to Smalltalk

43 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

44 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


Download ppt "Introduction to Smalltalk"

Similar presentations


Ads by Google