Pattern: Make Loops Apparent
...this pattern helps complete the SimplyUnderstoodCode pattern. This pattern helps solve the problem of making loops easy to understand in a chunk of code.
Loops are an instance of code that might not be read from top-to-bottom and therefore can be disorienting
People prefer to read code from top to bottom because that is how they read text. When a program cannot be understood reading linearly, disorientation can occur. A program that cannot be understood reading linearly typically has a non-linear control structure, and people sometimes need to read such programs in control-structure order.
Few programs have a purely linear control structure.
One of the most common examples of a non-linear control structure is the loop.
However, if a loop can be understood as whole or as a black box, the loop can be considered as an atomic unit in the program, and top-to-bottom text reading can be maintained.
Therefore, Make loops apparent and make their expression as idiomatic as possible.
There are various ways to achieve this. One is to use the loop operations in the programming language you're using. There is sometimes a temptation to use lower-level operations in the language to implement your own loops, but rarely does this result in easily understandable code. See the pattern UseBuiltInLoops.
Another way to achieve simply apparent loops is to use the mechanism for defining functions or procedures in the programming language you use. If you imagine that the parameters are the local variables in your loop, and a recursive call represents an iterative step, such a loop might be easily understood. See the pattern FunctionsForLoops.
Bad PHP programmers often find a new way to make loops unapparent, to wit:
{ ... pages and pages of code } while (condition)It's bad enough I already have to decipher PHP ;), but not even knowing you're in a loop until I get to the end makes Hulk very angry.