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...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Execute Around MethodHow do you represent pairs of actions that have to be taken together?It is common for two messages to an object to have to be invoked in tandem. When a file is opened,it has to be closed. When a context is pushed, it has to be popped.The obvious way to represent this is by publishing both methods as part of the external protocol ofthe object. Clients need to explicitly invoke both, in the right order, and make sure that if the first iscalled, the second is called as well. This makes learning and using the object more difficult, andleads to many defects, such as file descriptor leaks.Define a method that takes a Block as an argument. Name the method by appending “While:aBlock” to the name of the first method that needs to be invoked. In the body of the ExecuteAround Method, invoke the first method, evaluate the block, then invoke the second method.I learned this pattern from Cursor>>showWhile:Cursor>>showWhile: aBlock| old |old := Cursor currentCursor.self show.aBlock value.old showI use it lots of places. For example, I use it for making sure files get closed.Filename>>readStreamWhile: aBlock| stream |stream := self readStream.aBlock value: stream.stream closeYou will often want to wrap the Block evaluation in an exception handler so you are assured thesecond message gets sent.You need to give you method an Intention Revealing Selector.<strong>Coding</strong> <strong>Patterns</strong> page 34 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!