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.

YourselfYou need to use the value of a Cascade.How can you use the value of a Cascade if the last message doesn’t return the receiver of themessage.This has got to be the number one confusing method in all of <strong>Smalltalk</strong>. There it is in Object, whereevery new <strong>Smalltalk</strong>er stumbles across it:Object>>yourself^selfOr, if the programmer was really clever (and didn’t know about Interesting Return Value):Object>>yourselfWhat’s going on?Let’s say you want to add a bunch of elements to an OrderedCollection. Collection>>add: anObjectis defined to return anObject, not the receiver of the message. If you want to assign the Collectionto a variable:all := OrderedCollection newadd: 5;add: 7Will result in the value of all being 7. There are two solutions to this problem. The first is to put thevariable assignment in parentheses:(all := OrderedCollection new)add: 5;add: 7When you need the value of a Cascade and the last message does not return the receiver,append the message “yourself” to the Cascade.Our example becomes:all := OrderedCollection newadd: 5;add: 7;yourselfSending “yourself” returns the receiver, the new instance of OrderedCollection. That’s the objectthat gets assigned to the variable.I’ve seen folks become defensive about “yourself”, tacking it onto every Cascade they write. Youshouldn’t do this. Yourself is there to communicate to your reader that you really want the value ofthe receiver used, not the result of sending a message. If you aren’t using the value of a Cascade,don’t use yourself. For example, I wouldn’t use it in Point>>printOn:, because I don’t assign thevalue of the Cascade to a variable or return it as the value of the method.<strong>Coding</strong> <strong>Patterns</strong> page 137 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!