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.

DictionaryYou need a Collection that is indexed by something other than consecutive integers.How do you map one kind of object to another?Arrays and OrderedCollections map integers into objects. The integers must be between one andthe size of the collection. Dictionaries are more flexible maps. Their keys may be any objects,instead of having to be sequential integers.A typical use of a Dictionary is to map the names of things to the things:colors| result |result := Dictionary new.resultat: ‘red’put: (Color red: 1).resultat: ‘gray’put: (Color brightness: 0.5).^resultAnother way to solve this problem is to add a “name” instance variable to Color. In fact, this seemsto me the more “object-oriented” solution. Why doesn’t this work?Different parts of the system will want different names for the same color. A color called “red” inone place will be called “warning” in another. I suppose you could add a “colorName” and a“purposeName” instance variable to Color. Where would this end? Every new application of colorwould have to add a new instance variable. Much easier to use a Dictionary in each object thatneeds a unique name.Another way to solve this problem is to create an object that wraps a Color and gives it a name.NamedColorsuperclass: Objectinstance variables: name colorWhenever I have implemented an object like this, it never gains any more responsibility thanGetting Methods for the name and the wrapped object. It isn’t worth it to create a new object just todo that. Associating a name with a color using a Dictionary only takes a few lines and is easilyunderstood.Create a Dictionary if one object uniquely associates values with elements of a collection ofother objects. Make the keys the associated information and the values the other objects.Sometimes programmers in a hurry use Dictionaries as cheap data structures. You can always spotcode like this because two or more methods will use exactly the same fixed set of keys.<strong>Coding</strong> <strong>Patterns</strong> page 94 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!