vendredi 15 septembre 2017

Iterator/Range design, can a lightweight input iterator implemented with C++/java's iterator model?

I'd like to better understand Iterator/Range design decisions (focusing on InputIterators).

Basically, this is the java model:

while (iter.hasNext()) {
    Object o = iter.next();
    // do something with o
}

But, here is a quote from James Kanze:

Not that Java's iterators are perfect, either. The merge access and incrementing---as did the USL iterators. By the time Java was being developed, we'd already established that this wasn't a good idea, so it's hard to understand why they did it.

He says that merging access and incrementing is not a good idea. I was trying to find out the "why", but haven't found anything.

The "fixed" iterator look like this (which is the GoF iterator):

while (!iter.isDone()) {
    Object o = iter.element();
    // do something with o
    iter.next();
}

For C++1z, we could have the new range model. For InputRange, end() could return a special sentinel type, so handling end-of-stream condition can be optimized well.

Now, suppose that I want to create an InputRange (which is a lightweight range: doesn't store the read element), which read lines from a file/socket. Here, end-of-stream condition is only discovered after trying reading. The optimal iterator model could be this:

string line;
while (iter.getNext(line)) {  // getNext returns false at end-of-stream
    // do something with line
}

This iterator differs from any of the previous ones.

My questions are:

  • what are the cons of Java's iterator model (can you give an example of that)?
  • can my desired lightweight iterator be implemented with any of the mentioned iterator-types (java/GoF/C++)?

Aucun commentaire:

Enregistrer un commentaire