Name

CTL-05: Use a single EXIT in simple loops.

Synopsis

This best practice is another variation on “one way in, one way out.” It suggests that, whenever possible, you consolidate all exit logic in your simple loop to a single EXIT (or EXIT WHEN) statement.

In general, use the EXIT WHEN statement in place of code like this:

IF <> THEN EXIT; END IF;

because it’s more intuitive and requires less typing.

Example

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:

Did I reach the end of both files?
Are the lines different?
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;
   ELSIF (line1 != line2)
   THEN
      retval := FALSE;
      EXIT;
   ELSIF (file1_eof OR file2_eof)
   THEN
      retval := FALSE;
      EXIT;
   END IF;
END LOOP;

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;
END LOOP;

Sometimes it can be difficult to come up with just one EXIT statement. This usually occurs when you need to check a condition at the beginning and end of a loop. If you run into this situation, consider changing to a WHILE loop.

You should also be careful to initialize your return value and your loop terminator variable, to avoid unwanted NULL values that might disrupt your logic.

Benefits

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

Challenges

Depending on how badly the loop was written initially, you may need to perform substantial restructuring to improve the loop code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset