Refactoring Remove Control Flag
ProblemYou have a boolean variable that acts as a control flag for multiple boolean expressions.
SolutionInstead of the variable, use `break`, `continue` and `return`.
Control flags date back to the days of yore, when "proper" programmers always had one entry point for their functions (the function declaration line) and one exit point (at the very end of the function).
In modern programming languages this style tic is obsolete, since we have special operators for modifying the control flow in loops and other complex constructions:
break: stops loop
continue: stops execution of the current loop branch and goes to check the loop conditions in the next iteration
return: stops execution of the entire function and returns its result if given in the operator
- Control flag code is often much more ponderous than code written with control flow operators.
How to Refactor
Find the value assignment to the control flag that causes the exit from the loop or current iteration.
Replace it with
break, if this is an exit from a loop;
continue, if this is an exit from an iteration, or
return, if you need to return this value from the function.
Remove the remaining code and checks associated with the control flag.
Tired of reading?
No wonder, there are 7 hours worth of the text on this website.
Try out something different. We've just launched the interactive learning course on refactoring. It has more content and much more fun than a boring text.Learn more...
Everything is quite simple. This example is like video (but much cooler):
- After pressing the Play button, you will see floating messages, which will guide you through the example. You can proceed by clicking on them.
- You can fast-forward or return to previous steps by pressing arrow buttons on the left.
- Also, you can take a look at the code diff window, which will show what has changed in code during the example ()
- To check the code for errors, you can press "Compile and test" button ()