Loop Replacement
A Programming Pattern
Prof. David Bernstein
James Madison University
Computer Science Department
bernstdh@jmu.edu
Motivation
A Common Feature of Programs:
Nested Loops
A Common Shortcoming:
The code can be very difficult to read and understand when the bodies of the loops are complicated
A Solution
Loop Replacement:
Replace (one or more of) the inner loop(s) with a method call (often a
private
method)
An Observation:
This is really just a particular kind of functional decomposition
An Example - A Moving Average
The Description:
Each element in a moving average of a data array is the mean of the corresponding element in the data array and a fixed number of previous elements
The Math (0-Based Indexing):
\(m_i = \left( \sum_{i-n+1}^{i} d_i \right) / n, \text{ for } i = n-1, N-1\)
A Visualization:
Moving Average (cont.)
A "Naive" Implementation
javaexamples/programmingpatterns/LoopReplacement.java
(Fragment: 0)