collect: vs. to:do:

Bijan Parsia bparsia at email.unc.edu
Fri Oct 20 17:11:39 UTC 2000


On Fri, 20 Oct 2000, Dan Winkler wrote:

> A Smalltalk beginner's question...
> 
> In BookMorph>>getAllText I found this curious line:
> 
>         allText _ pages collect: [:pg | OrderedCollection new].
> 
> That seems to iterate over all the pages in the book, but not actually look at
> what it's iterating over.

Yep.

>  It just wants a collection of empty collections, one
> for each page.

Indeed.

>  Wouldn't it be cleaner to use a loop based on "1 to: pages size
> do:"

Certainly not :) This is a degenerate use of #collect: but perfectly
reasonable. Think about the extra cruft you'd have to add. First, you'd
need to determine *what kind* of collection pages is (right now it could
be anything!), then make a new one, save it to allText and then,
 in your block, add: a new OrderedCollection each iteration, well, if it
*supports* #add, which it may not. It could be an Array, in which case you
might be better off setting up a stream...

Bleah. Fragile and yucky and unclear!

Now say, in some future version, you want to do *more*, e.g., you want to
add the title of the page to each fresh OrderedCollection. Now you have a
*mess* of rewriting to do, since you have to figure out how to get ahold
of the page. As opposed to:
	pages collect: [:pg | OrderedCollection new add: pg title]



> instead of locating and then passing around each page without actually
> using it?

Er...This is very very very very very very cheap. They're just
references. Plus *you* aren't doing any locating or passing, so what do
you care? ;) A future compiler might even optimize this.

>  Or is this a Smalltalk idiom?

Remember: the enumeration protocal is my friend, the enurmeration protocol
is my friend. #do:, #collect:, #select: etc. are almost always prefereable
to some #to:do: loop and they're *always* cleaner. (There *may* be some
cases where inner loop logic takes over, but they're super rare.)

Cheers,
Bijan Parsia.






More information about the Squeak-dev mailing list