Modeling the Real World

In this chapter, you will learn how we model the real world using objects that send messages to communicate.

Self Driving Car

The example we saw in previous section looks more like a self driving car.

The Car object sends drive() to itself.

Self Driving Car

In code, it will look like this:

class Car
    p 'driving'

  p "Sender is : #{self}"
  p "Receiver is : #{binding.receiver}"

This prints:

Sender is : Car
Receiver is : Car

You can see that the sender and receiver is the Car class. The binding method provides us the execution context. We can retrieve the receiver object from the execution context.

Driver and Car

In reality, it's the driver who drives the car.

Driver Drives a Car

Sender and Receiver

Driver Drives a Car

Intent vs Implementation

What is intent?

I want to drive the car. We don't reach into the transmission and pull levers to drive the car. We step on the gas to drive the car. Your grandma can drive the car without knowing the details of the engine. She expresses her intent by using the public interface of the car.

What is implementation?

The things under the hood of a car is the implementation. Only your car mechanic knows about the details of the car engine. You may be aware of the 3.0 litre V-6 engine, but you have no idea how it works.

Background Job Processing

Let's see an example for code that reaches into the implementation details of a method.


This code knows that the implementation of the background processing class uses Singleton pattern. How can we fix this problem? To express the intent without any dependency on the implementation, we can re-write the code.


In this case, the client of the MyQueueClass is independent of the implementation details. We now have an intent revealing interface. This interface is stable. Tomorrow you may decide not to use the Singleton pattern, if so, the interface will not change.

Discovery Exercise

Write an example program to illustrate the fact that a driver drives a car. Hint: It will be like the Teacher-Student example we saw in Message Passing chapter.


In this chapter, we discussed how we model the real world using objects that send messages to communicate. We also saw how to separate the intent from the implementation to define intent revealing interface.

results matching ""

    No results matching ""