database

Never Use a RETURN Statement Inside a Loop

aircook 2006. 12. 26. 20:39

Never Use a RETURN Statement Inside a Loop


Unfortunately, such things have been known to happen. In the following example of terrifically poor programming practice, the FOR loop is interrupted—not with an EXIT, which would be unstructured enough, but with a RETURN statement:

BEGIN
   the_rowcount := Get_Group_Row_Count( rg_id );
  
   FOR j IN 1..the_rowcount
   LOOP
  
      col_val := Get_Group_Char_Cell( gc_id, j );
  
      IF UPPER(col_val) = UPPER(the_value)
      THEN
         RETURN j;
      END IF;
  
   END LOOP;
END;


Once again, if the loop should be conditionally terminated, do not use a FOR loop. Instead, use a WHILE or infinite loop and then issue the RETURN after the loop is completed. The following code replaces the unstructured IF statement shown above:

BEGIN
/* Initialize the loop boundary variables. */
   row_index := 0;
   the_rowcount := Get_Group_Row_Count (rg_id);
  
   /* Use a WHILE loop. */
   WHILE row_index <= the_rowcount AND
          match_not_found
   LOOP
         row_index := row_index + 1;
         col_val := Get_Group_Char_Cell (gc_id, row_index);
         match_not_found := UPPER (col_val) != UPPER (the_value)
   END LOOP;
  
   /* Now issue the RETURN statement. */
   RETURN row_index;
END;
The same rules apply to the use of a GOTO. If you use a GOTO to exit from a loop, you bypass the logical structure of the loop. You end up with code that is very difficult to trace, debug, fix, and maintain.