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.

Collecting ParameterYou have written an Intention Revealing Selector.How do you return a collection that is the collaborative result of several methods?One of the downsides of Composed Method is that it occasionally creates problems because oflinkages between the small methods. State that would have been stored in a temporary variable nowhas to be shared between methods.The simplest solution to this problem is to leave all the code in a single method and use temporaryvariables to communicate between the parts of the method. All the benefits you expect fromComposed Method vanish if you take this approach. The code is less revealing, more difficult toreuse and refine, and harder to modify.Another solution is to add an instance variable to the object that is shared only between themethods. This variable is very different than the other variables in the object. It is only valid whilethe methods are executing, not for the lifetime of the object. Instance variables should exist tocommunicate and store only state that must go together.We can solve the problem by adding an additional parameter that is passed to all the methods. Ihesitate to add layers of methods like this, except when they do useful work. In this case, becausethe other solutions aren’t valid, this is the right solution.Add a parameter that collects their results to all of the submethods.Here’s an example. The following code extracts all the married men and unmarried women from acollection of people:marriedMenAndUnmarriedWomen| result |result := OrderedCollection new.self people do: [:each | each isMarried & each isMan ifTrue: [result add: each]].self people do: [:each | each isUnmarried & each isWoman ifTrue: [result add: each]].^resultUsing Composed Method, we put each iteration into its own method:marriedMen| result |result := OrderedCollection new.self people do: [:each | each isMarried & each isMan ifTrue: [result add: each]].^resultunmarriedWomen| result |result := OrderedCollection new.self people do: [:each | each isUnmarried & each isWoman ifTrue: [result add: each]].^resultNow the question is how to compose the two methods. For an example this simple, I wouldprobably use Concatenation to write:<strong>Coding</strong> <strong>Patterns</strong> page 57 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!