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.

Equality MethodHow do you define equality for new objects?The message “=“ is sent 1363 times in the standard VisualWorks 2 image. It is implemented 57times. Clearly this is a message of considerable importance.The default implementation of equality is identity. Two objects are equal if and only if they are thesame object.Object>>= anObject^self == anObjectIf equality is only redefined 57 times, this definition must be good enough for the vast majority ofclasses.The most important reason for implementing equality is because you are going to put your objectsin a Collection and you want to be able to test for inclusion, remove elements, or eliminateduplicates in Sets without having to have the same instance.For example, let’s say I’m working on a library program. Two books are equal if the author andtitle are equal:Book>>= aBook^self author = aBook author & (self title = aBook title)A Library maintains an OrderedCollection of Books. Because I have defined equality, I can write amethod that takes the name of an author and a title and searches for that Book:Library>>hasAuthor: authorString title: titleString| book |book := Bookauthor: authorStringtitle: titleString.^self books includes: bookThe other major reason to implement equality is because your objects have to interoperate withother objects that implement equality. For example, if I was implementing a new kind of Number, Iwould define equality because all Numbers define equality.You see a fair number of class tests in equality methods. For example, you might see:Book>>= aBook(aBook isMemberOf: self class) ifFalse: [^false].^self author = aBook author & (self title = aBook title)I read this as “If aBook isn’t a Book, I couldn’t possibly be equal to it. Otherwise, I’m equal if myauthor and title are equal to aBook’s”. While class tests are in general a bad thing (see ChoosingMessage), this is one place where they can be useful. What if we want to add Videos to ourLibrary? Videos don’t have a message “author”, so comparing a Book and a Video without someprotection would result in an error.If you will be putting objects in a Collections or using them with other objects that defineequality, define a method called “=“. If you will be putting your objects in Collections withother objects, protect the implementation of “=“ so only objects of the same class will be fullytested for equality.<strong>Coding</strong> <strong>Patterns</strong> page 91 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!