Formatting Patterns Picks: Cascade

02 Dec 2014

Formatting (done right) makes code easy to read and understand. In a team, formatting code the same way is important because it helps each member feel comfortable working on a shared codebase.

Kent Beck defines ten Formatting Patterns for Smalltalk. I found the Cascade Pattern particularly interesting. Essentially it's a clean and simple way to pass multiple messages to one receiver. I haven't seen anything so simple in another language before (which is odd since in OOP we pass messages all the time).

A Cascade sends multiple messages to one receiver. Think of it as chaining, but each message goes to the first receiver.

In the following example, we send three messages to a rectangle instance:

rectangle color: Color red.
rectangle height: 10.
rectangle width: 20

In Smalltalk, we can write the code above as:

rectangle
    color: Color red;
    height: 10;
    width: 20

Simple, right?

Cascades can be misleading when used directly on a class, though:

Collection new
    add: 1;
    add: 2;
    add: 3

Remember each message is going to the first receiver, so the code in the example above will return a collection with only one entry (the number "3").

Use a Cascade to send several messages to the same receiver. Separate each message with a semicolon. Put each message on its own line and indent one tab. Only use Cascades for messages with zero or one argument. (Kent Beck)

Kent recommends that we use Cascades only to send messages with one or zero arguments, otherwise the readability gains are lost because the reader has to figure out which messages are being sent. E.g. in the code below we end up with two entries instead of one.

Collection new
    add: 1;
    add: 2
    add: 3

All in all I think this is a nice feature of Smalltalk that would be very useful in modern languages.

Reference