Essence of Dispatch

Taking Pharo Booleans as Example

Damien Cassou, Stéphane Ducasse and Luc Fabresse http://stephane.ducasse.free.fr

Objectives

Context: Booleans

In Pharo, Booleans have a superb implementation!

Three Exercises

  1. Implement not (Not)
  2. Implement | (Or)
  3. What is the goal of these exercises?

Exercise 1: Implement Not

Propose an implementation of Not in a world where:

   false not
   -> true

   true not
   -> false

Hint 1: No conditionals

The solution does not use conditionals (i.e., no if)

Hint 2: With Three Classes

Hint 2: Three Classes

Boolean Hierarchy

Hint 3: How do We Express Choice in OOP?

In OOP, choice is expressed

Example

   x open

Implementation of Not in Two Methods

False >> not
   "Negation -- answer true since the receiver is false."
   ^ true
True >> not
   "Negation -- answer false since the receiver is true."
   ^ false

Implementation Hierarchy

Not implementation.

Message Lookup is Choosing the Right Method

Not implementation.

Boolean Implementation

Boolean>>not
   "Abstract method. Negation: Answer true if the receiver is false, answer false if the receiver is true."
   self subclassResponsibility

Behavior of Or

true | true -> true
true | false -> true
true | anything -> true
false | true -> true
false | false -> false
false | anything -> anything

Implementation of Or in Boolean

Boolean >> | aBoolean
   "Abstract method. Evaluating Or: Evaluate the argument.
   Answer true if either the receiver or the argument is true."
   self subclassResponsibility

Implementation of Or in Class False

false | true -> true
false | false -> false
false | anything -> anything
False >> | aBoolean
   "Evaluating Or -- answer with the argument, aBoolean."
   ^ aBoolean

Implementation of Or in Class True

true | true -> true
true | false -> true
true | anything -> true
True >> | aBoolean
   "Evaluating Or -- answer true since the receiver is true."
   ^ true

Real Implementation of Or in Class True

The object true is the receiver of the message!

True>> | aBoolean
   "Evaluating disjunction (Or) -- answer true since the receiver is true."
   ^ true

So we can write it like the following:

True >> | aBoolean
   "Evaluating disjunction (Or) -- answer true since the receiver is true."
   ^ self

Or Implementation in Two Methods

Boolean hierarchy and instances.

Summary

/