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.

| s |s := Set new.Like an OrderedCollection, put ‘abc’ in once and it occurs once:s add: ‘abc’.s occurrencesOf: ‘abc” => 1But put it in again, and it still only occurs once:s add: ‘abc’.s occurrencesOf: ‘abc” => 1Take it out, and it’s gone:s remove: ‘abc’.s occurrencesOf: ‘abc” => 0(By the way, any time I’m trying to understand some new code I pull out a workspace and startfiddling like this. There is no better way to understand a new object than to grab an instance andstart sending it messages. If you think you know what’s going on, try to predict how it will react. Ifyou haven’t a clue, just start sending messages and see what comes back.)The elimination of duplicates comes at a cost. The order of adding and deleting thatOrderedCollection preserves is not available for Sets. Also, OrderedCollection responds to theindexed messages at: and at: put:. Sets do not.Create a Set.Sets probably cause me the most incompatibility problems of any of the Collection classes. I amforever passing a Set to a list pane that expects an indexable Collection. It is easy enough to solvethe problem by creating an Array or SortedCollection.ssnList: aPaneaPane contents: self ssnsbecomes:ssnList: aPaneaPane contents: self ssns asSortedCollectionSets perform an important communication function. They are your way of telling your reader “Iexpect duplicates in this Collection, but I don’t want them for further processing.” Be sure you onlyuse them when that is what you mean, because that’s how others will read you code.The other reason to use a Set is because its implementation of includes: is much faster than theimplementation in OrderedCollection (for large Collections). I have only done this a couple oftimes in my career, but it is a great trick to pull out when you’re tuning performance.If you implement an Equality Method for Set elements you must also implement a HashingMethod. You may need to convert to an Array or Temporarily Sorted Collection for clients whowant an indexable Collection.<strong>Coding</strong> <strong>Patterns</strong> page 90 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!