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.

IntervalHow do you represent a collection of numbers in sequence?Every once in a while you will find yourself writing code to create an Array and initialize itselements to sequential numbers:| indexes |indexes := Array new: 100.1 to: indexes size do:[:each |indexesat: eachput: each]This is not a very direct way to communicate “an Array of sequential numbers”. Also, it takesspace and time to represent an Array of numbers like this.There is a special collection class called Interval that is built expressly for this purpose. There isreally no down side to using Interval. Your code will read better and be faster.Create an Interval with start, stop, and an optional step value. The Constructor MethodsNumber>>to: and to:by: build Intervals for you.Some of the code you write using Intervals can be confusing at first.1 to: 20 do: [:each | ...]is equivalent to:(1 to: 20) do: [:each | ...]Even though the two phrases look similar, very different code is being invoked. In the first case, themessage to:do: is being sent to the SmallInteger 1. In the second, the message to: is being sent tothe SmallInteger 1. This returns an Interval that is then sent the message do:.You can translate prose descriptions of number sequences into Intervals:DescriptionIntervalOne to ten 1 to: 10Even numbers from zero to fifty 0 to: 50 by: 2Count down from 99 by threes 99 to: 0 by: -3Their are some enumerations you’d like to do that aren’t supported by the enumeration protocol.For example, although there is a Number>>to:do:, there isn’t a Number>>to:collect:. However, youcan use an Interval, because it is a full fledged collection.For example, if I have an Array and I want an Array of Associations, the keys of which are theindexes of the original Array and the values of which are the elements, I can write:<strong>Coding</strong> <strong>Patterns</strong> page 99 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!