Exception handling vs. hasNext()

Brendan Eich brendan at mozilla.org
Mon Nov 19 09:40:47 PST 2007


On Nov 19, 2007, at 7:51 AM, Garrett Smith wrote:

> So... I want to iterate over the keys in a Map.

Yuh-Ruey already replied, but I just wanted to point out that this:

for (let k in map.iterator::getKeys())
     print(k);

can be done simply via:

for (let k in map)
     print(k)

because the Map class provides the key iterator that its  
iterator::getKeys method returns from its default iterator::get  
method (which for-in calls) too. That is, by default, Map iteration  
returns keys.

If you want values or items (key/value pairs), you can get those too.  
To iterate over values, you might use:

for (let v in map.iterator::getValues())
     print(v);

but you should rather use the more succinct for-each-in loop:

for each (let v in map)
     print(v);

To iterate over items, use:

for (let [k, v] in map.iterator::getItems())
     print(k, v);

This item iteration case has no more concise form analogous to for- 
each-in, because if ES4 were always to map:

for (let [k, v] in map) ...

to:

for (let [k, v] in map.iterator::getItems()) ...

it would wrongly preempt destructuring of arbitrary properties from  
the value returned by the default iterator (the object returned by  
map.iterator::get()) -- it would prevent writing:

for (let [s, v, o] in tripledb) ...

where tripledb.iterator::get() returns an iterator over [subject,  
verb, object] triples.

If you feel the need to use a Java-like hasMore/getNext pattern, just  
lie down till the feeling goes away ;-). The Pythonic iteration  
protocol is simpler to use, more efficient to implement, and has no  
unchecked inconsistent state possibilities between hasMore and  
getNext. And yes, leveraging Python here is good reuse of language  
design, implementation experience, and user knowledge.

You do not need to catch StopIteration in any common cases. So don't  
fret about the fact that there's an exception thrown under the hood.  
Exceptions are not all errors.

/be





More information about the Es4-discuss mailing list