|
Consider a larger example. Every CA-Clipper program involves the
manipulation of data files, typically using the do while
construct. A common mistake is to forget to skip from one record to the
next. Here is the solution.
Suppose that you need to write a program that calculates and prints out
the average age of the employees in the accounting division. Start by
creating the template for the entire program.
01 procedure Main
02 local
03
04
05 return |
Then, considering how an average is calculated (total/count), add the
calculation at the end, and some matching local variables at the beginning.
Care should be taken to initialize the variables (another common mistake).
Also, open and close the EMPLOYEE table. Notice how symmetrical these
additions are. Add blank lines as needed.
01 procedure Main
02 local nAgeTotal:=0, nRecCount:=0
03 use EMPLOYEE new shared
04
05
06 close EMPLOYEE
07 ? "The average age is", nAgeTotal / nRecCount
08 return |
Now add a loop to navigate through the table. This will be the very common
do while construct. Note that the skip command
is not forgotten with this approach.
01 procedure Main
02 local nAgeTotal:=0, nRecCount:=0
03 use EMPLOYEE new shared
04 do while .not. eof()
05
06
07 skip
08 enddo
09 close EMPLOYEE
10 ? "The average age is", nAgeTotal / nRecCount
11 return |
Then, add the if...endif template for the test of the
DIVISION field.
01 procedure Main
02 local nAgeTotal:=0, nRecCount:=0
03 use EMPLOYEE new shared
04 do while .not. eof()
05 if EMPLOYEE->DIVISION == 'ACC'
06
07
08 endif
09 skip
10 enddo
11 close EMPLOYEE
12 ? "The average age is", nAgeTotal / nRecCount
13 return |
Finally, add the accumulation into the two variables.
01 procedure Main
02 local nAgeTotal:=0, nRecCount:=0
03 use EMPLOYEE new shared
04 do while .not. eof()
05 if EMPLOYEE->DIVISION == 'ACC'
06 nAgeTotal := nAgeTotal + EMPLOYEE->AGE
07 nRecCount := nRecCount + 1
08 endif
09 skip
10 enddo
11 close EMPLOYEE
12 ? "The average age is", nAgeTotal / nRecCount
13 return |
This technique can be extended to many areas of programming. For example,
the second-to-last line of the program was also created using the
Outside-In technique. It initially looked like this:
Once this was entered, the actual values were filled in to create the
complete line of code. Thus, the closing quote was not forgotten, neither
was the comma.
Although an experienced programmer could have created this program from
top to bottom in one go, as the code gets more complex the likelihood
of ommisions increases. Even in this "simple" example, the programmer
would have to remember to close out 7 code elements, among them the
if statement, the do while loop, and the
enclosing procedure itself.
|