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.

Hashing MethodYou have written an Equality Method. You may be putting new objects into a Set. You may beusing a new object as a key in a Dictionary.How do you ensure that new objects work correctly with hashed Collections?Once you understand the idea that you can override “=“, the world becomes your oyster. Newobjects that have their own definition of equality automatically begin to play nicely with the rest of<strong>Smalltalk</strong>. Almost.Collection>>includes: uses equality:Collection>>includes: anObjectself do: [:each | each = anObject ifTrue: [^true]].^falseSo you start out with an OrderedCollection and your newly equal objects and everything worksfine. Then you decide you need a Set. All of a sudden, you start getting bugs. You look at a Set andit has two objects in it that you know are equal. Weren’t Sets supposed to avoid that problem?The problem is that Set>>includes: doesn’t just send “=“, it also sends “hash”. If two objects areequal but they don’t return the same hash value, the Set is likely to miss the fact that they are equal.If you override “=“ and use the object with a hashed Collection, override “hash” so that twoobject that are equal return the same hash value.As it stands, this rule is kind of abstract. In practice, though, it is simple to satisfy this constraint.The Equality Method typically relies on some set of messages returning results that are equal:Book>>= aBook^self title = aBook title & (self author = aBook author)My first cut implementation of “hash” is to get the hash values of all the messages that the EqualityMethod relies on and put them together with bit-wise exclusive-or.Book>>hash^self title hash bitXor: self author hashThis works whether the messages return Strings, Numbers, Arrays, or whatnot, because all the subcomponentsobey the Hashing Method pattern.Hashing is often implemented in terms of Simple Delegation.<strong>Coding</strong> <strong>Patterns</strong> page 93 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!