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.

EnumerationHow do you execute code across a collection?Once you have a collection, you have to do something with it. Examples of computations acrosscollections are:An Account computes its balance by totaling up the values of all of its TransactionsA composite Visual displays by displaying all of its componentsDeleting a Directory deletes all of its FilesProcedural programmers develop a toolbox of idioms for writing code like this. Ask a Cprogrammer to iterate over an array and chances are they will be able to program as fast as they cantype. Visual recognition of such code becomes automatic, also.<strong>Smalltalk</strong> hides the details of iteration behind a set of uniform messages that all collectionsunderstand. Rather than have one or two or three line idioms, <strong>Smalltalk</strong> uses single word messages.Code written using these messages is easy to write correctly and easy to read correctly.Because there are several variations on the enumeration messages, some <strong>Smalltalk</strong> programmerslearn one or two and code the rest by hand. In the end, it takes longer to write code that is bigger,more error prone, and harder to read than if they just used the messages that are there.Use the enumeration messages to spread a computation across a collection.Enumeration messages work fine for empty collections. You can use this to avoid special case codefor the case that a collection is empty.printChildrenchildren isEmpty ifTrue: [^self].self children do: [:each | each print]is exactly the same as:printChildrenself children do: [:each | each print]Use Do for simple enumeration. Use Collect to transform the elements of a collection. UseSelect/Reject to select only certain portions of a collection. Use Detect to search for an element.Use Inject:Into: to keep a running total across a collection.<strong>Coding</strong> <strong>Patterns</strong> page 105 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!