Friday, July 15, 2005

( Try to ) Exit once

Here's part of a program that compares two files for equality.
After reading the next line from each file, it checks for the following
conditions:
  1. Did it reach the end of both files?
  2. Are the lines different?
  3. Did I reach the end of just one file?
In each case, set the "return value" for the function and also issue an EXIT statement:
LOOP
read_line (file1, line1, file1_eof);
read_line (file2, line2, file2_eof);

IF (file1_eof AND file2_eof)
THEN
retval := TRUE;
EXIT; -- first time
ELSIF (line1 != line2)
THEN
retval := FALSE;
EXIT; -- Second time repeated
ELSIF (file1_eof OR file2_eof)
THEN
retval := FALSE;
EXIT; -- Third time repeated
END IF;
END LOOP;


Sometimes it can be difficult to come up with just one EXIT statement.
This usually occurs when we need to check a condition at the beginning
and end of a loop.
We should also be careful to initialize your return value and
your loop terminator variable, to avoid unwanted NULL values that
might disrupt your logic.


Then rewrite this loop body as follows

LOOP
read_line (file1, line1, file1_eof);
read_line (file2, line2, file2_eof);

IF (file1_eof AND file2_eof)
THEN
retval := TRUE;
exit_loop := TRUE;
ELSIF (line1 != line2)
THEN
retval := FALSE;
exit_loop := TRUE;
ELSIF (file1_eof OR file2_eof)
THEN
retval := FALSE;
exit_loop := TRUE;
END IF;
EXIT WHEN exit_loop; -- Only one time
END LOOP;

A single EXIT is especially important in large, complex loop bodies;
It allows you to more easily trace and debug your code.

Challenges lies on how badly the loop was written initially,
we may need to perform substantial restructuring to improve the loop
code.


0 comments: