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.

DetectHow do you search a collection?Another common collection idiom is searching for an element that meets certain criteria. Of course,you can implement this using do: by testing the criteria inside the enumeration block and thenexecuting some code conditionally. This code gives the car keys to the first responsible child:self children do: [:each | each isResponsible ifTrue: [each giveKeys: self carKeys. ^self]]Notice that you have to be sure to only execute the conditional code once. Managing this in acomplex loop can result in code that is very hard to follow.Search a collection by sending it detect:.Detect takes a one argument block as an argument, which should evaluate to true or false. It returnsthe first element for which the block evaluates to true. The code above turns into:(self children detect: [:each | each isResponsible]) giveKeys: self carKeysThere is a variation of detect:, detect:ifNone: that takes an additional zero parameter Block as anargument. Use this if you’re not sure any element will be found.Detect:ifNone: gives rise to a clever (“hard to read, at least at first”) idiom. What if you want toreturn true from a method if any element meets a criterion and false otherwise?hasResponsibleChildself childrendetect: [:each | each isResponsible]ifNone: [^false].^trueI use this occasionally, but I can’t say I’m particularly proud of it.Use a Simple Enumeration Parameter in the first block argument. Use a Lookup Cache to optimizeperformance.<strong>Coding</strong> <strong>Patterns</strong> page 109 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!