while( true )
The following code should be considered bad form, regardless of language or desired functionality:
while( true ) {
}
Reasons
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.
- Is more difficult to prove as correct.
Alternative to Goto
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
).