Always close iterators?

Bergi a.d.bergi at web.de
Thu Mar 26 02:12:07 UTC 2015


Axel Rauschmayer schrieb:
>wouldn’t the iteration protocol be simpler if iterators were always 
closed (versus only if iteration finishes abruptly)?

Hm, I can't see much harm in that, it seemd to simplify the 
implementation of iterators indeed. It changes the semantics from

| cleanup must be done before returning the iterresult

(that's how `finally` works) to

| after having returned the iterresult, you will be made to clean up

Or, actually, that doesn't sound as good. "Some will *hopefully* tell 
you" to clean up is not what looks like good, resilient design.

While it does indeed simplify the producer implementation, the consumer 
side does get more complicated - from

   for (let iter=getIterator(), value, done; {value,done}=iter.next(), 
!done; ) {
       console.log(value);
       // Assuming this never throws
   }

to

   let iter = getIterator();
   for (let value, done; {value,done}=iter.next(), !done; ) {
       console.log(value);
       // Assuming this never throws
   }
   iter.return(); // additional line required

Of course, if done properly (accounting for exceptions) the change is 
minimal - from try-catch to try-finally. But who does that, how often is 
it forgotten?

  Bergi


More information about the es-discuss mailing list