This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Which loop is recommended for getting values from list?

 
ankur rathi
Ranch Hand
Posts: 3830
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which loop is recommended for retrieving values from a list - for or while. I like while loop with iterator, but can't force my whole team to use that because don't have justification to this...

Please help me out.
Thanks a lot.
[ June 17, 2005: Message edited by: rathi ji ]
 
Roger Chung-Wee
Ranch Hand
Posts: 1683
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I won't have thought that you need to force people to adopt a particular style for this, there are usually far more important things to worry about. For what it is worth, my way of coding is like this:
 
Tim West
Ranch Hand
Posts: 539
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
IMO it is reasonable for a coding standard to mandate a particular style. I agree with Roger on the choice: 'for' is much better in this case. Consider the following:



There is a bug in this which is obvious when you're looking for it, but can be missed if you're not. That is, in the second while() loop, we're using the wrong iterator. This is often a copy/paste error - and not necessarily an obvious one one, since the iterator 'iter' has no more elements, so the second while() loop is silently skipped.

If this code is written using for() loops, the scope of the Iterator prevents this error from occurring.

That all said, this has nothing to do with performance...it's a matter of coding style


-Tim
 
ankur rathi
Ranch Hand
Posts: 3830
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Notice that in Java 5, the "right" thing to do is


[ June 21, 2005: Message edited by: Ilja Preuss ]
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic