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.

CollectionHow do you represent a one-to-many relationship?Every programming language provides facilities to represent one-to-many relationships. The firstdata structure in FORTRAN was the array.Computer science has made a franchise of representing one-to-many relationships. How manythousands of varieties of trees, lists, and tables are there hidden away in the Journals of the ACM?Such an important topic has picked up a vast quantity of idiom in every programming language.Even though I hardly use C any more, I can instantly recognize:for (i = 0; i < n; i++) ...as iterating over an array.One of the most brilliant early developments in <strong>Smalltalk</strong> was presenting a unified protocol to allthe varieties of ways of representing one-to-many relationships. No longer does all client codedirectly encode how to iterate over elements. Iteration is the responsibility of the objectrepresenting the relationship itself. This results in tremendous power throughout development. Youcan change from a linear list to a hash table by changing “OrderedCollection” to “Set”, with theconfidence that no other code will be affected.The down side of the Collection classes is their very power. Because you can write code involvingCollections in a very few words, you have to be initiated in the special meaning of those wordsbefore you have a chance of understanding such code. Once you understand the vocabulary,though, you will never be able to write code in a language without support for Collections withouta wistful sigh about “how easy this would be in <strong>Smalltalk</strong>”.There is an alternative to using the Collection classes. Any class can be made indexable, that ishave both named variables and variables you access through at: and at:put:. Using this feature, anyclass can be made to act like both a regular object and a collection at the same time. This would beuseful if you were extremely tight on space, but copying the Collection code just isn’t worth it.Create a Collection to represent the one-to-many relationship.Use an OrderedCollection for Collections that change size dynamically. Use an Array for fixedsizedCollections. Use a Set to ensure element uniqueness. Use a Dictionary to map from one kindof object to another. Use a Temporarily Sorted Collection for ordering elements. Use aSortedCollection to keep elements in a computed order.<strong>Coding</strong> <strong>Patterns</strong> page 86 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!