Premise
The following code should be considered bad form, regardless of language or desired functionality:
while( true ) {
}
Supporting Arguments
The while( true )
loop is poor form because it:
- Breaks the implied contract of a while loop.
- The while loop declaration should explicitly state the only exit condition.
- Implies that it loops forever.
- Code within the loop must be read to understand the terminating clause.
- Loops that repeat forever prevent the user from terminating the program from within the program.
- Is inefficient.
- There are multiple loop termination conditions, including checking for "true".
- Is prone to bugs.
- Cannot easily determine where to put code that will always execute for each iteration.
- Leads to unnecessarily complex code.
- Automatic source code analysis.
- To find bugs, program complexity analysis, security checks, or automatically derive any other source code behaviour without code execution, specifying the initial breaking condition(s) allows algorithms to determine useful invariants, thereby improving automatic source code analysis metrics.
- Infinite loops.
- If everyone always uses
while(true)
for loops that are not infinite, we lose the ability to concisely communicate when loops actually have no terminating condition. (Arguably, this has already happened, so the point is moot.)
Alternative to "Go To"
The following code is better form:
while( isValidState() ) {
execute();
}
bool isValidState() {
return msg->state != DONE;
}
Advantages
No flag. No goto
. No exception. Easy to change. Easy to read. Easy to fix. Additionally the code:
- Isolates the knowledge of the loop's workload from the loop itself.
- Allows someone maintaining the code to easily extend the functionality.
- Allows multiple terminating conditions to be assigned in one place.
- Separates the terminating clause from the code to execute.
- Is safer for Nuclear Power plants. ;-)
The second point is important. Without knowing how the code works, if someone asked me to make the main loop let other threads (or processes) have some CPU time, two solutions come to mind:
Option #1
Readily insert the pause:
while( isValidState() ) {
execute();
sleep();
}
Option #2
Override execute:
void execute() {
super->execute();
sleep();
}
This code is simpler (thus easier to read) than a loop with an embedded switch
. The isValidState
method should only determine if the loop should continue. The workhorse of the method should be abstracted into the execute
method, which allows subclasses to override the default behaviour (a difficult task using an embedded switch
and goto
).
Python Example
Contrast the following answer (to a Python question) that was posted on StackOverflow:
- Loop forever.
- Ask the user to input their choice.
- If the user's input is 'restart', continue looping forever.
- Otherwise, stop looping forever.
- End.
Code
while True:
choice = raw_input('What do you want? ')
if choice == 'restart':
continue
else:
break
print 'Break!'
Versus:
- Initialize the user's choice.
- Loop while the user's choice is the word 'restart'.
- Ask the user to input their choice.
- End.
Code
choice = 'restart';
while choice == 'restart':
choice = raw_input('What do you want? ')
print 'Break!'
Here, while True
results in misleading and overly complex code.