Essence of Dispatch
Taking Pharo Booleans as Example
Damien Cassou, Stéphane Ducasse and Luc Fabresse
http://stephane.ducasse.free.fr
Objectives
- Understanding of message passing (late binding)
- the heart of OOP
- more an OOP lecture than a Pharo one
- Insight at how beautiful Pharo's implementation is
Context: Booleans
In Pharo, Booleans have a superb implementation!
&
, |
, not
(eager)
or:
, and:
(lazy)
ifTrue:ifFalse:
, ifFalse:ifTrue:
Three Exercises
- Implement
not
(Not)
- Implement
|
(Or)
- What is the goal of these exercises?
Exercise 1: Implement Not
Propose an implementation of Not in a world where:
- You have:
true
, false
- You only have objects and messages
- How would you implement the message
not
?
Hint 1: No conditionals
The solution does not use conditionals (i.e., no if
)
Hint 2: With Three Classes
- The solution uses three classes:
Boolean
(abstract), True
and False
true
is the singleton instance of True
false
is the singleton instance of False
Hint 2: Three Classes
Hint 3: How do We Express Choice in OOP?
In OOP, choice is expressed
- By defining classes with compatible methods
- By sending a message to an instance of such class
Example
x
can be a file, a window, a tool,...
- The method is selected based on
x
's class
Implementation of Not in Two Methods
Implementation Hierarchy
Message Lookup is Choosing the Right Method
Boolean Implementation
Boolean
is abstract
- Subclasses are
True
and False
and implement
- logical operations
&
, not
- control structures
and:
, or:
, ifTrue:
, ifFalse:
, ifTrue:ifFalse:
, ifFalse:ifTrue:
Behavior of Or
Implementation of Or in Boolean
Implementation of Or in Class False
Implementation of Or in Class True
Real Implementation of Or in Class True
The object true
is the receiver of the message!
So we can write it like the following:
Or Implementation in Two Methods
Summary
- The solution to implement booleans' operations:
- does NOT use conditionals (if)
- lets the receiver decide
- Do not ask, tell
/