13.07.2015 Views

Smalltalk Best Practice Patterns Volume 1: Coding - Free

Smalltalk Best Practice Patterns Volume 1: Coding - Free

Smalltalk Best Practice Patterns Volume 1: Coding - Free

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CascadeHow do you format multiple messages to the same receiver?The simplest solution is to just repeat the expression that created the receiver. Such code looks likethis:self listPane parent color: Color black.self listPane parent height: 17.self listPane parent width: 11.For complex expressions, the first simplification is to use an Explaining Temporary Variable tohold the value of the expression:| parent |parent := self listPane parent.parent color: Color black.parent height: 17.parent width: 11.One of <strong>Smalltalk</strong>’s few syntactic quirks is a solution to this problem. Rather than having to repeatan expression or create a temporary variable to hold the expression, <strong>Smalltalk</strong> lets you say at theend of one message “and here’s another message to the same receiver”.Use a Cascade to send several messages to the same receiver. Separate the messages with asemicolon. Put each message on its own line and indent one tab. Only use Cascades formessages with zero or one argument.The code above becomes:self listPane parentcolor: Color black;height: 17;width: 11Whether or not you use a Cascade is really a matter of intent. If you want to communicate “here area bunch of messages all going to the same object”, that’s a good time to use a Cascade. If you justhappen to be sending messages to the same object, but it’s not really part of the essence of the codethat the two messages are going to the same object, don’t use a Cascade.One confusion that sometimes arises about Cascade is if the initial expression is complex, where dothe cascaded messages get sent? For example, in:OrderedCollection newadd: 5;add: 10the indentation cues you that both add’s get sent to the new OrderedCollection, not the class itself.Here’s the rule: all subsequent messages in a Cascade go to the same receiver as the first messagein the cascade (in this case, #add:). Any preceding parts of the expression that got you the receiverare irrelevant.The restriction that Cascades only be used with zero or one argument messages comes from thedifficulty in visually parsing Cascades with varying numbers of arguments. In the example above,what if you could send height:width: as a single message? Using Cascade, the code would looklike:<strong>Coding</strong> <strong>Patterns</strong> page 135 of 147 9/30/2006

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!