Pattern: '''Use Built-in Loops''' ...this pattern helps satisfy MakeLoopsApparent. ---- A complicated loop can lead to disorientation and confusion. Loops are one of the hardest code fragments to understand, because people can best understand code when they can read that code from top to bottom visually in the text and when the important pieces all fit on one page or screen. Often, people writing loops think in terms of low-level concepts or anthropomorphic concepts such as "just do it again until I'm done" and are tempted to use low-level programming language constructs to mimic this logic. But, not everyone shares this private language of iteration, and so it will not always be easy for a code reader sometime later to comprehend the loop. Such a code reader will become disoriented and perhaps will cause an error while modifying that code. Many programming languages have a variety of loop constructs. ''Therefore,'' Use a programming language loop construct where it makes sense. ---- Deciding where it makes sense is the hard part. Some people will try to use this pattern at all costs, and the result might be code that is extremely disorienting or confusing. Here are some simple tests to apply to see whether a loop construct is right for a complicated task - it is usually easy to see whether it works for a simple task. * Does the loop construct have the right name for the basic iterative action? * Does it have the right options to hold the parameters, to test for completion, and to express exceptional cases? * Does its name and options correspond to a statement you might make to a colleague while describing the loop? * If the construct supports automatic loop variable updating, does your use of the construct use simple update expressions? * Let the code sit for a day or two; when you return, is the loop clear? Show the loop to a colleague but don't explain it; does it make sense to that colleague? Explain the loop to a colleague; do you feel comfortable and confident? * Does your use of it exhibit a balance of the parts of the loop construct? If one of these tests fails, try the pattern FunctionsForLoops or BuildLoopsYourself. ---- CategoryLoops