본문 바로가기

database

Never Use a RETURN Statement Inside a Loop

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.

'database' 카테고리의 다른 글

ORACLE 캐릭터셋 변경  (0) 2007.02.27
다중 Row 결과를 단일행으로 컴마로 분리해 출력하는 방법  (0) 2007.01.23
EXECUTE IMMEDIATE  (0) 2006.12.16
오라클 테이블정보 쿼리  (0) 2006.12.06
SQL%ROWCOUNT  (0) 2006.11.28