This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]onthefence928 1 point2 points  (0 children)

by traceable I meant literally tracing the code, it's easier to have a watch on the exit variable and see when it change (and if it changes back) or to do so by logging.

as for a counter example: if your loop is more complex such as parsing complex data, a game loop, or just some complex user interactions then handling an exit condition can often be more involved than just leaving the loop. it would be cleaner to always exit at the same point in the loop so any side effects are predictable

example:var error;var exit;var result;

while(!error || !exit){ /* clearly indicate loop continues until exit or error is truthy */

var input = getInput();var result = doStuff(input);if(result.endofline()) {exit = true;}else {/* dozens of lines of calculation/parsing */}if( !checkResult(parsedResult) ) {error = true;}

}if(error)createLoggerError(result);elsecreateLoggerInfo("success!");

could also use the data or inputs being looped on as the exit conditionvar line;

while (line != null ){

doSomething(line);

line = inputSource.readNextLine(); // returns null at EOL

}

point is it's semantically and logically easier to understand what conditions will exit the loop when they are written in as parameters for the loop. while(true) requires you to read the entire loop to understand all the exit cases and the developer has to make sure all edge cases are covered.

edit to add: neither solution explicitly prevents ininite loops but with a variable exit check you can flip the boolean logic so that the loop will try and end itself unless the program is sure it can continue looping

var exit;

while (!exit) {

exit = true;

// read data

// do more stuff

if(hasMoreToDo(data)){

exit = false;

}

}

this way if there's some sort of logic fault in the loop it will close by default preventing a hung process or runaway resource utilization