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.

Includes:How do you search for a particular element in a collection?Many people’s first instinct is to use the enumeration protocol to implement searching. They willwrite code like this:| found |found := false.aCollection do: [:each | each = anObject ifTrue: [found := true]]....With more experience, you might see a more sophisticated enumeration message:| found |found := (aCollectiondetect: [:each | each = anObject]ifNone: [nil]) notNil....The collection protocol provides you with a message to do exactly this, includes:.The above code would look like this using includes:| found |found := aCollection includes: anObject...You could probably even eliminate the temporary variable and just use the expression in line.Importantly, includes: is available to be optimized. Some kinds of collections, like Set, execute itindependently of the size of the collection. The code fragments above will always take timeproportional to the size of the collection.To search a collection for an object, send includes: and pass the object to be searched for.You will have to implement an Equality Method and a Hashing Method for your own objects if youwant to search based on contents instead of identity.<strong>Coding</strong> <strong>Patterns</strong> page 103 of 147 9/30/2006

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

Saved successfully!

Ooh no, something went wrong!