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.

CollectHow do you operate not on the objects in a collection, but the result of a message sent to eachobject in the collection?If this was good old procedural programming, we’d probably write code where the enumerationblock sent a message to the element, then used the result of the message in further computation.self children do: [:each | self passJudgement: each hairStyle]Other code that also wanted to deal with hair styles would have similar code:self children do: [:each | self trim: each hairStyle]This violates the once and only once rule. The two code fragments look very similar except for theoperation to be performed on the hair style.We can capture the commonality of the code by creating an intermediate collection that containsthe results of the messages sent to each element of the original collection. We can then enumerateover the new collection.The new clarity of the code comes at the cost of allocating a new collection to hold the transformedelements and iterating over the collection twice, once to transform it and once to compute with it. Ifyou measure a performance problem with coming from intermediate collections, it is easily fixedlater. Better communication is definitely worth the cost, and chances are you’ll never have aperformance problem because of it.Use collect: to create a new collection whose elements are the results of evaluating the blockpassed to collect: with each element of the original collection. Use the new collection.We can use Composed Method with collect: to capture the common part of the above code:childrenHairStyles^self children collect: [:each | each hairStyle]Then we can simplify the code fragments:self childrenHairStyles do: [:each | self passJudgement: each]self childrenHairStyles do: [:each | self trim: each]If you must, improve performance of code using collect: with a special Enumeration Method. Use aSimple Enumeration Parameter in the block argument.<strong>Coding</strong> <strong>Patterns</strong> page 107 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!