Skip to content

G-4340: Always use a NUMERIC FOR loop to process a dense array.

Major

Maintainability

Reason

It is easier for the reader to see, that the complete array is processed.

Since an exit statement is similar to a goto statement, it should be avoided, whenever possible.

Please note that:

  • Varrays are always dense
  • Associative arrays (or index-by tables) are either dense or sparse
  • Nested tables start dense and may become sparse

Example (bad)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
declare
   type t_employee_type is varray(10) of employees.employee_id%type;
   t_employees   t_employee_type;
   co_himuro     constant integer        := 118;
   co_livingston constant integer        := 177;
   co_min_value  constant simple_integer := 1;
   co_increment  constant simple_integer := 1;
   i             pls_integer;
begin
   t_employees := t_employee_type(co_himuro,co_livingston);
   i           := co_min_value;

   <<process_employees>>
   loop
      exit process_employees when i > t_employees.count();
      sys.dbms_output.put_line(t_employees(i));
      i := i + co_increment;
   end loop process_employees;
end;
/

Example (good)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
declare
   type t_employee_type is varray(10) of employees.employee_id%type;
   t_employees   t_employee_type;
   co_himuro     constant integer := 118;
   co_livingston constant integer := 177;
begin
   t_employees := t_employee_type(co_himuro,co_livingston);

   <<process_employees>>
   for i in 1..t_employees.count()
   loop
      sys.dbms_output.put_line(t_employees(i));
   end loop process_employees;
end;
/