Opinion poll: for loop vs while loop with Iterators.

Discussion in 'Java' started by Daniel Pitts, Dec 21, 2006.

  1. Daniel Pitts

    Daniel Pitts Guest

    Java 1.5 finaly gave us an elegant for each construct, but for-each
    lacks the ability to manipulate the underlying Iterable structure.

    Generally, the way to do this is (in pseudo-code:)

    Obtain the iterator.
    L: Check if it has a next element
    get the next element
    process the element.
    repeat from L

    This can be coded in Java a few ways.
    // For method:
    for (Iterator<E> iterator = iterable.iterator(); iterator.hasNext(); )
    {
    E e = iterator.next();
    if (shouldRemove(e)) {
    iterator.remove(e);
    }
    }

    // vs
    // While method:
    Iterator<E> iterator = iterable.iterator();
    while (iterator.hasNext()) {
    E e = iterator.next();
    if (shouldRemove(e)) {
    iterator.remove(e);
    }
    }

    Both approaches have their pros and cons, but I'm interested to see
    what people think.

    I'll post my opinion later.
    Daniel Pitts, Dec 21, 2006
    #1
    1. Advertising

  2. Daniel Pitts

    Karl Uppiano Guest

    "Daniel Pitts" <> wrote in message
    news:...
    > Java 1.5 finaly gave us an elegant for each construct, but for-each
    > lacks the ability to manipulate the underlying Iterable structure.
    >
    > Generally, the way to do this is (in pseudo-code:)
    >
    > Obtain the iterator.
    > L: Check if it has a next element
    > get the next element
    > process the element.
    > repeat from L
    >
    > This can be coded in Java a few ways.
    > // For method:
    > for (Iterator<E> iterator = iterable.iterator(); iterator.hasNext(); )
    > {
    > E e = iterator.next();
    > if (shouldRemove(e)) {
    > iterator.remove(e);
    > }
    > }
    >
    > // vs
    > // While method:
    > Iterator<E> iterator = iterable.iterator();
    > while (iterator.hasNext()) {
    > E e = iterator.next();
    > if (shouldRemove(e)) {
    > iterator.remove(e);
    > }
    > }
    >
    > Both approaches have their pros and cons, but I'm interested to see
    > what people think.
    >
    > I'll post my opinion later.


    I tend to use the while pattern for no particularly good reason except that
    the increment expression is not used in the for pattern. I guess it offends
    my sense of esthetics, which is reason enough to tip the balance, all else
    being equal. I might change my mind if someone can demonstrate a big
    advantage one way or the other.
    Karl Uppiano, Dec 21, 2006
    #2
    1. Advertising

  3. Daniel Pitts

    Daniel Dyer Guest

    On Thu, 21 Dec 2006 20:40:45 -0000, Daniel Pitts
    <> wrote:

    > Java 1.5 finaly gave us an elegant for each construct, but for-each
    > lacks the ability to manipulate the underlying Iterable structure.
    >
    > Generally, the way to do this is (in pseudo-code:)
    >
    > Obtain the iterator.
    > L: Check if it has a next element
    > get the next element
    > process the element.
    > repeat from L
    >
    > This can be coded in Java a few ways.
    > // For method:
    > for (Iterator<E> iterator = iterable.iterator(); iterator.hasNext(); )
    > {
    > E e = iterator.next();
    > if (shouldRemove(e)) {
    > iterator.remove(e);
    > }
    > }
    >
    > // vs
    > // While method:
    > Iterator<E> iterator = iterable.iterator();
    > while (iterator.hasNext()) {
    > E e = iterator.next();
    > if (shouldRemove(e)) {
    > iterator.remove(e);
    > }
    > }
    >
    > Both approaches have their pros and cons, but I'm interested to see
    > what people think.
    >
    > I'll post my opinion later.


    The for loop is one line shorter but I've always preferred the while
    loop. It justs seems more natural and more readable to me. When I was at
    school, programming in BASIC and Pascal with less flexible for loops, for
    loops were for a fixed number of iterations known at the start, and while
    loops for an indeterminate number of iterations. With an iterator, you
    don't know how many iterations are required until you've finished (you can
    find out, but it's more work). So reading code that says "while there are
    more elements do x" just seems more correct.

    Dan.


    --
    Daniel Dyer
    http://www.uncommons.org
    Daniel Dyer, Dec 21, 2006
    #3
  4. Daniel Pitts

    bjeremy Guest

    Daniel Pitts wrote:
    > Java 1.5 finaly gave us an elegant for each construct, but for-each
    > lacks the ability to manipulate the underlying Iterable structure.
    >
    > Generally, the way to do this is (in pseudo-code:)
    >
    > Obtain the iterator.
    > L: Check if it has a next element
    > get the next element
    > process the element.
    > repeat from L
    >
    > This can be coded in Java a few ways.
    > // For method:
    > for (Iterator<E> iterator = iterable.iterator(); iterator.hasNext(); )
    > {
    > E e = iterator.next();
    > if (shouldRemove(e)) {
    > iterator.remove(e);
    > }
    > }
    >
    > // vs
    > // While method:
    > Iterator<E> iterator = iterable.iterator();
    > while (iterator.hasNext()) {
    > E e = iterator.next();
    > if (shouldRemove(e)) {
    > iterator.remove(e);
    > }
    > }
    >
    > Both approaches have their pros and cons, but I'm interested to see
    > what people think.
    >
    > I'll post my opinion later.


    In "Effective Java" by Josh Bloch (p. 142 for all those who wish to
    check this), Josh argues that we should prefer using for loops as
    opposed to while loops. His reasoning is that the loop structure allows
    us an opportunity to limit the scope of variables. The for loop enables
    us to declare loop variables and thus limit their scope to the exact
    region needed. His caveat is if you happen to need the variable after
    the execution of the loop, you probably don't want to make it a loop
    variable.
    bjeremy, Dec 21, 2006
    #4
  5. Daniel Pitts

    Daniel Pitts Guest

    bjeremy wrote:
    > Daniel Pitts wrote:
    > > Java 1.5 finaly gave us an elegant for each construct, but for-each
    > > lacks the ability to manipulate the underlying Iterable structure.
    > >
    > > Generally, the way to do this is (in pseudo-code:)
    > >
    > > Obtain the iterator.
    > > L: Check if it has a next element
    > > get the next element
    > > process the element.
    > > repeat from L
    > >
    > > This can be coded in Java a few ways.
    > > // For method:
    > > for (Iterator<E> iterator = iterable.iterator(); iterator.hasNext(); )
    > > {
    > > E e = iterator.next();
    > > if (shouldRemove(e)) {
    > > iterator.remove(e);
    > > }
    > > }
    > >
    > > // vs
    > > // While method:
    > > Iterator<E> iterator = iterable.iterator();
    > > while (iterator.hasNext()) {
    > > E e = iterator.next();
    > > if (shouldRemove(e)) {
    > > iterator.remove(e);
    > > }
    > > }
    > >
    > > Both approaches have their pros and cons, but I'm interested to see
    > > what people think.
    > >
    > > I'll post my opinion later.

    >
    > In "Effective Java" by Josh Bloch (p. 142 for all those who wish to
    > check this), Josh argues that we should prefer using for loops as
    > opposed to while loops. His reasoning is that the loop structure allows
    > us an opportunity to limit the scope of variables. The for loop enables
    > us to declare loop variables and thus limit their scope to the exact
    > region needed. His caveat is if you happen to need the variable after
    > the execution of the loop, you probably don't want to make it a loop
    > variable.


    My personal preference is the while loop.

    I agree that limiting the scope of temporary variables is useful,
    however, there are clearer ways to accomplish this. My personal
    favorite is to introduce a method that does the work of the loop. That
    has the added benefit of explaining what the loop does, by giving it a
    name.

    Alternatively, to limit the scope other ways you can do stuff like:

    public static void main(String...args) {
    {
    final int myInt = 0;
    System.out.println(myInt);
    }
    {
    final int myInt = 2;
    System.out.println(myInt);
    }
    }
    Daniel Pitts, Dec 21, 2006
    #5
  6. Daniel Pitts

    Lew Guest

    Daniel Pitts wrote:
    > My personal preference is the while loop.


    I much prefer the for loop, except when there is no loop variable.

    I notice that the sun rises and sets irrespective of my preference, though.

    - Lew
    Lew, Dec 22, 2006
    #6
  7. Daniel Pitts

    Daniel Pitts Guest

    Lew wrote:
    > Daniel Pitts wrote:
    > > My personal preference is the while loop.

    > I much prefer the for loop, except when there is no loop variable.


    My opinion on the for statement:
    It is useful when there are 2 simple statements (initializer and
    post-loop), one conditional expression, and 1 more statement (compound
    or otherwise)

    The iterator concept does NOT fall into that category, unless you write
    it like this:
    E e;
    for (Iterator<E> i = getIterator(); i.hasNext(); doSomething(e)) {
    e = i.next();
    }

    Which IMHO is ugly.

    Although, like you said
    > I notice that the sun rises and sets irrespective of my preference, though.

    Happens to be true of me too.
    Daniel Pitts, Dec 22, 2006
    #7
  8. Daniel Pitts

    bjeremy Guest


    > The iterator concept does NOT fall into that category, unless you write
    > it like this:
    > E e;
    > for (Iterator<E> i = getIterator(); i.hasNext(); doSomething(e)) {
    > e = i.next();
    > }
    >
    > Which IMHO is ugly.
    >



    How's this then?

    for (Iterator<E> i = getIterator(); i.hasNext(); ){
    doSomething(i.next());
    }
    bjeremy, Dec 22, 2006
    #8
  9. Daniel Pitts

    Lew Guest

    Daniel Pitts wrote:
    > My opinion on the for statement:
    > It is useful when there are 2 simple statements (initializer and
    > post-loop), one conditional expression, and 1 more statement (compound
    > or otherwise)


    That use case lies far over toward the "for" end of the seesaw.

    > The iterator concept does NOT fall into that category, unless you write
    > it like this:
    > E e;
    > for (Iterator<E> i = getIterator(); i.hasNext(); doSomething(e)) {
    > e = i.next();
    > }
    >
    > Which IMHO is ugly.


    That use case lives nearer the middle.

    I happen to like that idiom, except that I declare "E e" inside the loop and
    put the doSomething() there, too, but I understand perfectly well why it seems
    ugly.

    I rarely will put a workhorse expression inside the for () setup; they belong
    in the body.

    My version would be (assuming a collection as the progenitor of the iterator):

    for ( Iterator<E> iter = collection.getIterator(); iter.hasNext(); )
    {
    E entry = iterator.next();
    doSomething( entry ); // or just doSomething( iterator.next() )
    }

    In most cases, that becomes

    for( E entry : collection )
    {
    doSomething( entry );
    }

    anyway, and the ugliness vanishes very far.

    > Lew wrote:
    >> I much prefer the for loop, except when there is no loop variable.


    I lied. I use for() {}, while () {} and do {} while ();.

    I prefer all three. I like "for ( ;; )" to set up unbounded loops.

    - Lew
    Lew, Dec 22, 2006
    #9
  10. Lew wrote:
    > I prefer all three. I like "for ( ;; )" to set up unbounded loops.


    Yuck! I have always used (and usually see everyone else use) "while
    (true)"...
    John Ersatznom, Dec 22, 2006
    #10
  11. Daniel Pitts

    Lew Guest

    > Lew wrote:
    >> I prefer all three. I like "for ( ;; )" to set up unbounded loops.


    John Ersatznom wrote:
    > Yuck! I have always used (and usually see everyone else use) "while
    > (true)"...


    Yuck? Here we have a perfectly useful idiom purpose-built to handle just this
    situation. I wonder why that seems so hideous to you.

    It's nice to have choices.

    - Lew
    Lew, Dec 22, 2006
    #11
  12. Lew wrote:
    >> Lew wrote:
    >>> I prefer all three. I like "for ( ;; )" to set up unbounded loops.

    >
    > John Ersatznom wrote:
    >> Yuck! I have always used (and usually see everyone else use) "while
    >> (true)"...

    >
    > Yuck? Here we have a perfectly useful idiom purpose-built to handle just
    > this situation. I wonder why that seems so hideous to you.
    >
    > It's nice to have choices.
    >
    > - Lew


    The difference is that the first time I saw a "for(;;)" I had to think
    to work out that it was going to loop forever. It depends on
    understanding the effect of omitting the continuation test.

    The first time I saw a "while(true)" it was instantly obvious that the
    intent was to loop as long as true is true.

    Patricia
    Patricia Shanahan, Dec 22, 2006
    #12
  13. Daniel Pitts

    Ed Guest

    bjeremy skrev:


    >
    > In "Effective Java" by Josh Bloch (p. 142 for all those who wish to
    > check this), Josh argues that we should prefer using for loops as
    > opposed to while loops. His reasoning is that the loop structure allows
    > us an opportunity to limit the scope of variables. The for loop enables
    > us to declare loop variables and thus limit their scope to the exact
    > region needed. His caveat is if you happen to need the variable after
    > the execution of the loop, you probably don't want to make it a loop
    > variable.


    Seconded, FWIW.

    ("Sun, arise!")

    ..ed

    --

    www.EdmundKirwan.com - Home of The Fractal Class Composition
    Ed, Dec 22, 2006
    #13
  14. Daniel Pitts

    Lew Guest

    Patricia Shanahan wrote:
    > The difference is that the first time I saw a "for(;;)" I had to think
    > to work out that it was going to loop forever. It depends on
    > understanding the effect of omitting the continuation test.
    >
    > The first time I saw a "while(true)" it was instantly obvious that the
    > intent was to loop as long as true is true.


    You seem to imply that a computer language should be explicable to those who
    do not know that language.

    There is a case for that. OTOH, the for ( ;; ) idiom has been around for
    decades and should be familiar to anyone versed in the C/Java family of languages.

    OTOOH, I might switch to using while ( true ) myself for the very reason you
    state.

    OTOOOH, the for ( ;; ) construction is so ugly-cute, and ugly-clever, and
    ugly-elitist, that I don't think I will ever give it up entirely.

    - Lew
    Lew, Dec 23, 2006
    #14
  15. Lew wrote:
    > Patricia Shanahan wrote:
    >> The difference is that the first time I saw a "for(;;)" I had to think
    >> to work out that it was going to loop forever. It depends on
    >> understanding the effect of omitting the continuation test.
    >>
    >> The first time I saw a "while(true)" it was instantly obvious that the
    >> intent was to loop as long as true is true.

    >
    > You seem to imply that a computer language should be explicable to those
    > who do not know that language.
    >
    > There is a case for that. OTOH, the for ( ;; ) idiom has been around for
    > decades and should be familiar to anyone versed in the C/Java family of
    > languages.


    "know the language" is not a binary state. I prefer my code to be
    readable by as many people as possible.

    I have trouble imagining someone understanding "for(;;)" but not
    "while(true)". I'm not so sure the other way round.

    Patricia
    Patricia Shanahan, Dec 23, 2006
    #15
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. corona
    Replies:
    0
    Views:
    397
    corona
    Oct 14, 2003
  2. Replies:
    21
    Views:
    665
    spinoza1111
    May 10, 2008
  3. birdsong

    select.poll.poll() never blocks

    birdsong, Feb 12, 2009, in forum: Python
    Replies:
    2
    Views:
    450
    birdsong
    Feb 12, 2009
  4. Jean-Paul Calderone

    Re: select.poll.poll() never blocks

    Jean-Paul Calderone, Feb 12, 2009, in forum: Python
    Replies:
    3
    Views:
    440
    birdsong
    Feb 12, 2009
  5. Isaac Won
    Replies:
    9
    Views:
    372
    Ulrich Eckhardt
    Mar 4, 2013
Loading...

Share This Page