File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Cattle Drive and the fly likes loops Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » This Site » Cattle Drive
Bookmark "loops" Watch "loops" New topic


paul wheaton

Joined: Dec 14, 1998
Posts: 20543

I just finished the first whack at describing how to use a loop. I would appreciate feedback. See

permaculture Wood Burning Stoves 2.0 - 4-DVD set
Frank Carver

Joined: Jan 07, 1999
Posts: 6920
I bet you guessed I'd have an opinion, didn't you... In general it's OK, but I think you are doing "for" a "do while" loops a bit of a disservice.
Detailed comments:
1. Be a little careful here. Java loops are not exactly the same as C/C++ loops. In java the expression between the parentheses of a while or in the middle of a for must be a strict boolean. In C/C++ it may be any expression which is automatically converted by applying the non-zero rule.
2. Where you say:
<pre>while( )
I would prefer that you put some sort of "tokens" in the parentheses and the braces, like:
<pre>while (boolean-expression)
some stuff
You do it for the "for" case.
If you think a concept like "boolean-expression" hasn't been explained yet, you can always refer out to another page.
3. I can see why you advocate using "done", but one of the readability tweaks that I try and apply to software I maintain is "test the positive case, not the negative". It helps avoid the easy-to-miss use of "!" and makes adding extra conditions using && and | | a lot less error prone. In your case I might say:
<pre>boolean waitingForEsc = true ;
while ( waitingForEsc )
if ( userPressedEsc() )
waitingForEsc = false ;
System.out.println("not done yet");
4. You say:
The "while loop" can be used for all of your looping needs.
Personally, I would stress the "can" rather than the "all", to imply that you never really need another type of loop, but they are available, and do have their place.
5. I think you should really justify why you dislike the other methods of exiting a loop ("break", "continue" and "return"). Just a blanket "don't" doesn't equip the student to evaluate their use in other peoples code, and can sometimes lead to over-complicated solutions. As with other things, I would try to find at least one case or rule of thumb for where they are useful, to show that they aren't in most cases. Similarly, I think you should mention or link to a page with a discussion of exceptions and how they can inadvertantly exit loops before they have completed.
6. I think you are a little harsh on "for". I tend to use for loops more than while loops, as most cases I encounter have the same structure:- setup, check, and move on.
For example, I find a case like:
<pre>for (String s = in.readLine(); s != null; s = in.readLine())
do a lot of stuff involving s
easier to read and maintain, as both "readLine" calls are in one place. There is a lot less chance of missing one if it needs to be modified, or inadvertently excluding it with an "if" in the body of the loop.
I consider the rule of thumb for use of a for loop is can you simply identify the three phases ("setup", "check", and "move on"), should the "move on" phase happen every time round the loop, is the "setup" only used in this one loop?
Also you say:
The "for loop" shorthand for this is:
int i ;
for( i = 0 ; i < 10 ; i++ )
System.out.println( i );
I would always say:
for(int i = 0 ; i < 10 ; i++ )
System.out.println( i );
to emphasize the fact that i only makes sense in the context of the loop.
7. I know you don't like do..while, (I don't, really) but you ought to describe it in a little more detail. Just ranting about how it should never be used is not really helping the student. I feel it's better to give at least a rule of thumb for when it should be used, and by implication that it shouldn't be used in all other cases.
I'm particularly worried by "When you have to try to explain to somebody what it is and why you use it". I may be tough, but I require that all people who work on projects with me know the language and tools they are using. If they are unfamiliar with something I get them trained up so they recognise it and know when and when not to use it The attitude "avoid parts of the language just because some readers might not know about them" has led to some of the worst code I have ever seen (admittedly, its opposite; "I'm just learning the language, so I'll use every single feature, however obscure or pointless" is just as bad).
The problem is where do you stop. You regard "do..while" as too difficult, but I have enountered people who never use ++, --, += etc., using "a = a + 1" instead. I'm currently involved in a running "discussion" with a colleague who regards ?: as akin to black magic.
8. I applaud your introduction of some style issues, but it opens possibilities for a lot of other good hints. A few that I would like to see are:
8.1 Recommend explicitly the layout you use, (start and end blocks on the same column as the loop keyword; always have a block, even for only one statement) and justify it in terms of catching subtle "while(stuff);" bugs and making it easier to add extra code in the loop (especially temporary diagnostic print-outs).
8.2 Discuss what can be put in the "boolean" part of a while or for loop, and recommend that only simple expressions or boolean variables be used. Actively discourage the old C habit of putting assignments or other side-effects there.
8.3 Discuss the case of degenerate loops where there is no "body" (this is especially common with for loops used to scan things) and recommend a syntax to express these clearly (ie. avoid "for(...);" or "while(..);")
8.4. Discuss "always loops" eg. while(true), for( ; ; ) and recommend a syntax.
8.5. Discuss and discourage the use of loops as timers. This is a rare habit these days, but I still occasionally encounter the likes of:
<pre>// wait for a while
for (int i = 0; i < 1000; ++i)
[This message has been edited by Frank Carver (edited April 07, 1999).]

Read about me at ~ Raspberry Alpha Omega ~ Frank's Punchbarrel Blog
paul wheaton

Joined: Dec 14, 1998
Posts: 20543

Excellent post! If you don't mind, I would like to cut and paste what you said into a web page and make a link to it at the bottom of loop.html.
In response to your list:
1) VERY good point. I will try to work that in somewhere.
2) Excellent suggestion. I will try to come up with something like that.
3) You make the ultimate point about testing the positive instead of the negative. But I've never come up with a generic positive that I like. Usually I want to stop the loop for more than one reason. So "waitingForEsc" won't work. I used to use "okay", "peachy" and "keepGoing", but I felt that they did not make my code as readable as "done". So I trade a negation for readability. A good trade in my book.
4) I like the way I do it. I'm trying to emphasize that it is possible to use the while loop for everything. Later I clarify that there are times that it is best to use a for loop.
5) I think that any experienced programmers will probably skip this page. So my audience is beginners. I don't want to overwhelm them. BUT! I think you have inadvertantly provided the ultimate solution. By posting your message as a link along with these comments I'm making, this issue will be covered. Here is my response:
I have never found a need for using "continue". When I examine what it does, it simply looks like poor programming practice. I think that anyone that is attempting to use "continue" should re-examine their code and find a way to complete their algorithm without it. Because, IMO, they are doing it wrong.
Any use of "break" outside of a switch statement falls into the same category as "continue".
Any use of "return" outside of being the last line in a method falls into the same category as "continue".
6a) I think that your example for loop is more complicated than the same thing as a while loop. Getting everything on one line doesn't make it clearer. Think of the first time you saw an "advanced" use of a for loop in C. I bet you had to re-read it six times before you got a goo
Don't get me started about those stupid light bulbs.
subject: loops