Premise
The following code should be considered bad, regardless of language or desired functionality:
while( true ) { }
Supporting Arguments
The while( true ) is bad because it:
- Terminates the implied while loop contract.
- A while loop declaration must explicitly indicate a single exit condition.
- Assumes he will be forever.
- The code inside the loop must be read in order to understand the termination proposal.
- Cycles that are repeated forever do not allow the user to complete the program from the program.
- Ineffective.
- There are several conditions for ending a loop, including a true check.
- It is prone to errors.
- It is impossible to determine where to put the code that will be executed for each iteration.
- Leads to overly complex code.
Go to alternative
The following code looks better:
while( isValidState() ) { execute(); } bool isValidState() { return msg->state != DONE; }
Benefits
There is no flag. No goto . No exceptions. Easy to change. Easy to read. Easy to fix. In addition, the code:
- Isolates knowledge of the cycle workload from the cycle itself.
- Allows someone to maintain code to easily extend functionality.
- Allows you to assign multiple completion conditions in one place.
- Separates a ending sentence from code to execute.
- Safer for nuclear power plants .; -)
The second point is important. Not knowing how the code works, if someone asked me to make the main loop so that other threads (or processes) have some processor time, two solutions come to mind:
Option number 1
Readily insert a pause:
while( isValidState() ) { execute(); sleep(); }
Option number 2
Replace execution:
void execute() { super->execute(); sleep(); }
This code is simpler (therefore easier to read) than a loop with a built-in switch . The isValidState method should only determine if the loop should continue. The workhorse of the method should be abstracted to the execute method, which allows subclasses to override the default behavior (a difficult task using the built-in switch and goto ).
Python example
Contrast the following answer (to a Python question) that was posted on StackOverflow:
- Loop forever.
- Ask the user to enter their choice.
- If user input is a βrestartβ, continue the loop forever.
- Otherwise, stop the cycle forever.
- To the end.
The code
while True: choice = raw_input('What do you want? ') if choice == 'restart': continue else: break print 'Break!'
Versus:
- Initialize user selection.
- Loop, while user choice is the word "reboot".
- Ask the user to enter their choice.
- To the end.
The code
choice = 'restart'; while choice == 'restart': choice = raw_input('What do you want? ') print 'Break!'
Here, while True leads to misleading and overly complex code.
Dave Jarvis Sep 14 '09 at 7:14 2009-09-14 07:14
source share