Build Loops Yourself

Pattern: Build Loops Yourself

...use this pattern when you cannot apply the patterns UseBuiltInLoops or FunctionsForLoops.


Sometimes loops are not simple. Disorientation is unavoidable.

When the patterns UseBuiltInLoops and FunctionsForLoops cannot be used, you will need to build loops yourself from low-level constructs. In this case you will need to make the code as understandable as you can by supplying documentation and careful annotation.

Therefore, Use the patterns for SimplyUnderstoodCode as thoroughly as you can to help you write the loop. Write documentation for the code in English and in mathematical notation. Have the code and its design reviewed thoroughly.


This is the difficult case in programming. Read texts like Knuth to understand the trade-offs between efficiency and understandability.
I don't think this says enough. Maybe something along the lines of EncapsulateLoops??

(I've not created a page for this yet partly because I'm not completely happy with the word "loop". I suspect the concept of "iteration" is deeper. A loop is a means, not an end.)

Suppose you have some data structure like a tree, for which the code to iterate over it is relatively complicated. Try to encapsulate that complication in a class, like the VisitorPattern or an IteratorPattern. If your language supports closures, use them - write a method which takes a closure argument and invokes it for each iteration of the loop. If not, use inheritance and virtual methods to build CallBackFunction?(s), to the same effect. Or (probably better), use the TemplateMethodPattern - so that specific iterations are subclasses of the class that holds the iteration logic.

Smalltalk uses this approach extensively - it has no built-in loops. Java uses iterators plus normal loops (it calls them Enumerations), but there is an argument that this approach is only good in the absence of closures. Eiffel uses the TemplatePattern approach.

-- DaveHarris

(Please correct my links - I don't know where all the patterns are described on this site.)


I like using an apply where the container is in charge of iteration. This allows the container to control locking without having to worry whether applications behave correctly.

EditText of this page (last edited February 22, 2006) or FindPage with title or text search