Over at Vox, Randal is showing some interesting methods he found in Smalltalk for iterating collections. The really interesting thing he found is that Collections in Squeak support #keysAndValuesDo: .

I was quite surprised by this because the method name is not really intention revealing or hinting at its purpose. If I want to iterate over a collection and also need the index of an element I’d use myList doWithIndex: [:item :index| …] rather than #keysAndValuesDo:.The latter is of tremendous help when working with Dictionaries and LookupTables (hash collections) and makes life much easier for a code maintainer.

One of the commenters said VA ST implements keysAndValuesDo: only for keyed collections, which I think is a good thing. Using keysAndValuesDo: polymorphically on completely different types of collections is not helping the reader of the code very much. “Heck, what does he mean with a Key, it’s just a list of customers? I must have missed something. What the heck is he doing there?”

Randal also presents a very nice new way of using do:separatedBy:

| index |
index := 1.
myItems do: [:item | ... ] separatedBy: [ index := index + 1 ].

I’d never ever have thought of this one, but this surely looks familiar to many developers. Not that this is actually bad code, but why add so much syntactical noise to a simple job?

One of Smalltalk’s strengths is that it sometimes makes complex things easy to do and – even more important – to read. The messages supported by the Collection hierarchy are a really bright example here.