Java Reference
In-Depth Information
Do not read the implementation of the first statement, which is given in Fig.
7.6 as a statement-comment (see Sec. 13.3.3). The purpose of the statement-com-
ment is to let you focus on one thing at a time. When reading the outer loop,
focus on what this statement does. Later, you can go back and see how this state-
ment is implemented by reading the code following it up until the first blank line.
And when focusing on how this statement is implemented, put the rest of the pro-
gram out of your mind.
This ability to read at various levels of abstraction is important, for it lets
you separate your concerns and focus on one thing at a time. Focus is the impor-
tant point here.
Some people will tell you that nested loops —one loop appearing in the
repetend of another— are difficult to understand. They are, if loops are not prop-
erly annotated or well structured. But in our view, the program segment of Fig.
7.6 does not have nested loops! The repetend of the outer loop is:
The point made
in this para-
graph is much
better made in
Activity 7-6.2!
Set fresh variable b to "i is prime ";
if (b) { x= x + 1; }
and, in this view, there is no concept of a loop.
7.7.2
How not to program
A student developed the code of Fig. 7.7. We have abstracted away from the task
and cleaned up the code in order to make it easier to make our point. The pro-
gram did not work correctly, and it took him a long time to find out that c need-
ed to be set to 0 when r was incremented, as shown below:
// Process pairs (r,c) , for 0≤r<R , 0≤r<C
int r= 0; int c= 0;
while (r != R) {
while (c != C)
{ Process pair (r,c); c= c + 1; }
r= r + 1; c= 0;
Activity
7-6.3
}
But this code is not well designed. The handling of variable c —initializing
// Process pairs (r,c) , for 0≤r<R , 0≤r<C
int r= 0; int c= 0;
while (r != R) {
while (c != C) {
Process pair (r , c); c= c + 1;
}
r= r + 1;
}
Figure 7.7:
A program segment with an error
Search WWH ::




Custom Search