Home
Loops with at most one iteration should be refactored
Description
The "Loops with at most one iteration should be refactored" rule for PL/SQL code states that any loops that contain only one iteration should be replaced with simpler code. This is because loops are designed to execute a set of instructions multiple times, and a loop with only one iteration is redundant and can be replaced with simpler code. Refactoring loops with only one iteration can help improve code readability and maintainability, as well as reduce the amount of code needed to achieve the same result.
Key Benefits
- Reduced Complexity: Refactoring loops with at most one iteration can reduce complexity and make the code easier to read and understand.
- Improved Performance: Refactoring loops with at most one iteration can improve performance by reducing the number of operations that need to be performed.
- Simplified Maintenance: Refactoring loops with at most one iteration can simplify maintenance by making it easier to identify and fix bugs.
Non-compliant Code Example
DECLARE
id customers.id%type;
name customer.name%type;
address customers.address%type;
CURSOR customers_c is
SELECT id, name, address FROM customers;
BEGIN
OPEN customers_c;
<<INNER_LOOP>>
LOOP --Non compliant code (Loops with one iteration)
FETCH customers_c into id, name, address;
EXIT WHEN customers_c%notfound;
dbms_output.put_line(id || ' ' || name || ' ' || address);
END LOOP INNER_LOOP;
CLOSE customers_c;
END;
Compliant Code Example
DECLARE
id customers.id%type;
name customer.name%type;
address customers.address%type;
CURSOR customers_c is
SELECT id, name, address FROM customers;
BEGIN
OPEN customers_c; --Compliant code (No need of loop for single iteration)
FETCH customers_c into id, name, address;
EXIT WHEN customers_c%notfound;
dbms_output.put_line(id || ' ' || name || ' ' || address);
CLOSE customers_c;
END;