Understanding Messages
Damien Cassou, Stéphane Ducasse and Luc Fabresse
http://stephane.ducasse.free.fr
Objects, Messages and Closures
- We only manipulate objects (mouse, booleans, arrays, numbers, strings, ...)
- We only send them messages (@, +, not, getPng:, ifTrue:ifFalse:, new, ...)
- and we use closures
Syntax
- Originally invented for kids
- Programs look like little sentences
- Try to minimize the number of parentheses
Example
Three Kinds of Messages to Minimize Parentheses
- Unary message:
receiver selector
- Binary message:
receiver selector argument
- Keyword message:
receiver key1: arg1 key2: arg2
Message Precedence
(Msg) > Unary > Binary > Keywords
- First we execute
()
- Then unary, then binary and finally keyword messages
This order minimizes ()
needs
But let us start with messages
Unary Message Examples
Did you notice?
- We sent messages to any objects, including classes!
- There is no difference between sending a message to an object or to a class
A Bit of Introspection
- Returns all the messages the class understands
A Little Query
- Let us query the system and only filter the unary messages:
select:
is an iterator (see Iterator lecture)
- Easy :-)
Binary Messages
- Used for arithmetic, comparison and logical operations
- One, two or three characters taken from:
- + - / \ * ~ < > = @ % | & ! ? ,
Binary Message Examples
Keyword Messages
equivalent to:
Test Yourself!
1 log
Browser open
2 raisedTo: 5
'hello', 'world'
10@20
point1 x
point1 distanceFrom: point2
Test Yourself!
1 log
(unary)
Browser open
(unary)
2 raisedTo: 5
(keyword)
'hello', 'world'
(binary)
10@20
(binary)
point1 x
(unary)
point1 distanceFrom: point2
(keyword)
Example: Message setX:
- We change the x value of the receiver (a point)
- No parentheses required
Example: Message at:put:
#(...)
creates an array
at:put:
changes the value of the array element.
- arrays start at 1 in Pharo (i.e., first element is at index 1)
Example: Message between:and:
- The message
between:and:
is sent to an integer
- Takes two arguments
10
and 20
Summary
Three kinds of messages: unary, binary and keywords
- Unary
- Binary
- Keywords-based messages
/