3 ms·
Edited, basically do not use while loops, if you do tread carefully and provide yourself an exit. You don't want to be the one that nukes the server.
by drawkbox 9y ago
Edited, basically do not use while loops, if you do tread carefully and provide yourself an exit. You don't want to be the one that nukes the server.
- RobertRoberts 9y agoI learned about while loops at the beginning of my career, and after a few scary errors, I never used them again. 20 years of no while loops anywhere... never going back.
- contravariant 9y agoDijkstra's approach towards provably correct programs has changed my opinion on loops somewhat. Among all types a 'while' loop gives the strongest mathematical guarantees. In particular it ensures a condition is true at the start of each iteration, and is false when exiting the while loop. Combining this with loop invariants leads to precise and straightforward to verify code. Avoiding while loops to ensure an exit just seems to be sacrificing a lot of power in exchange for some pretty shaky guarantees that your loop will finish. Although in the majority of cases where a while loop could be used you're simply iterating over some (implicit) data structure. In which case it's obviously better to make this explicit using a "for ... in" loop.
- ajuc 9y agoDid you mean to use for with no counter instead? If so - I strongly disagree. I much prefer while(condition) {} to for (;condition;) {} For one thing you can't misplace ";" in a while loop. I agree that "do while" loops are unintuitive and rarely used, and thus the place to first check for bugs. Also they save very little so I just implement them as do(); while usually. But I know people who disagree about that, too, and shout at me for avoiding them:) It seems what's unintuitive for me isn't so for others.
- drawkbox 9y agoBasically what I am saying is while should be mostly off limits. But yes if you end up in a loop you have some sort of counter/null checks or way out if you end up in a constant/recursive loop. Never leave open the possibility of a lock due to being stuck in a loop.
- ajuc 9y agoYou want to write "cat" equivalent. How do you do the loop? I think for loops should be limited to iteration over collections, or repeating sth known number of times. There are cases when you need to decide if you want to continue iteration on the fly, and while loop is the perfect tool for that. Also while loop is arguably less error-prone than for loop: can't swap clauses because there's just one, can't write "," instead of ";" by mistake.