Name

CTL-04: Never EXIT or RETURN from WHILE and FOR loops.

Synopsis

The WHILE and FOR loops include “boundary conditions” that determine:

  • When and if a loop should execute at all

  • When a loop should stop executing

If you use the EXIT or RETURN statements inside a WHILE or FOR loop, you cause an unstructured termination from the loop. The resulting code is hard to trace and debug.

Example

Here’s the bottom half of a function that scans the contents of a collection and returns the row in which a match is found.

   l_count := titles.COUNT;
   FOR indx IN 1 .. l_rowcount 
   LOOP
      IF l_match_against = titles(indx)
      THEN
         RETURN indx;
      END IF;
   END LOOP;

   RAISE Exit_Function;
EXCEPTION
   WHEN Exit_Function THEN RETURN NULL;
END;

Now this is some nasty code. You manage to get all the way down to the end of the executable section, and you are punished with an exception! See [MOD-07: Limit functions to a single RETURN statement in the execution section.] for how this violates best practice for a “funnel-shaped” function.

Of course, you’re not supposed to get to the end of the function. Instead, the function finds a match and zooms straight out of the function with a RETURN.

Now imagine a function whose body is 200 lines long with nested loops and several different RETURNs in different parts of the loop. Chaos!

Benefits

By following the maxim “one way in and one way out” for your loops, the resulting code is much easier to understand and debug. If your loop needs to execute at least once (like a Pascal REPEAT statement), you’re better off using a simple LOOP construct and testing for the exit condition with EXIT WHEN.

Challenges

Your exit test in the WHILE expression can become a bit more complex, especially when you have to replace a natural FOR loop with a more mechanical WHILE loop. For example, you have a FOR loop expression that iterates over nested_table.FIRST to nested_table.LAST, but you need to terminate the loop when you find a matching entry. In order to put the exit test in the iteration scheme, you have to now use a WHILE loop, initialize and maintain a loop control variable yourself (for the current offset), and test for the exit condition in the WHILE expression.

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

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