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 Temporary VariableSometimes a Temporary Variable is used to collect intermediate results.How do you gradually collect values to be used later in a method?The right set of enumeration protocol would make this question moot. Inject:into: in particularoften eliminates the need for a temporary variable. Code like:| sum |sum := 0.self children do: [:each | sum := sum + each size].^sumCan be rewritten as:^self childreninject: 0into: [:sum :each | sum + each size]The variety of enumeration strategies in complex programs makes it impossible to generalize theinject:into: idiom. For example, what if you want to merge two collections together so that youhave an element from collection a, and element from collection b, and so on. This would require aspecial enumeration method:^self leftFingerswith: self rightFingersinject: Array newinto: [:sum :eachLeft :eachRight |(sum copyWith: eachLeft) copyWith: eachRight]It is much simpler to create a Stream for the duration of the method:| results |results := Array new writeStream.self leftFingers with: self rightFingers do:[:eachLeft :eachRight | results nextPut: eachLeft; nextPut: eachRight].^results contentsWhen you need to collect or merge objects over a complex enumeration, use a temporaryvariable to hold the collection or merged value.Role Suggesting Temporary Variable Name explains how to name the variable.<strong>Coding</strong> <strong>Patterns</strong> page 79 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!