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.

SetYou need a Collection with unique elements. You may need a Collecting Parameter withoutduplicates. You may have been using an OrderedCollection.How do you represent a Collection whose elements are unique?Suppose you have a Collection of Accounts and you want to send statements to all of the Owners.You don’t have an explicit Collection of the Owners anywhere. You only want to send a singlestatement to each Owner. Each Owner could have a number of different Accounts.How can we get each Owner only once? The naive code doesn’t work right:owners| results |results := OrderedCollection new.self accounts do: [:each | results add: each owner].^resultsWe may get multiple copies of an Owner. You could solve this problem yourself by checkingwhether an owner was in the results before adding it:owners| results |results := OrderedCollection new.self accounts do:[:each || owner |owner := each owner.(results includes: owner) ifFalse: [results add: owner]].^resultsSets solve this problem for you by ignoring “add: anObject” if anObject is already part of the Set.Using a Set instead of an OrderedCollection fixes the problem.owners| results |results := Set new.self accounts do: [:each | results add: each owner].^resultsAnother way of looking at the difference is by trying both Collections out in a workspace:| o |o := OrderedCollection new.Put the String ‘abc’ in the Collection and it occurs once:o add: ‘abc’.o occurrencesOf: ‘abc’ => 1Put it in again, and it occurs twice:o add: ‘abc’.o occurrencesOf: ‘abc’ => 2Take it out once, and it only occurs once:o remove: ‘abc’.o occurrencesOf: ‘abc” => 1Sets show different behavior.<strong>Coding</strong> <strong>Patterns</strong> page 89 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!