Home
FOR loop end conditions should not be hard - coded
Description
The rule "FOR loop end conditions should not be hard-coded" means that the end conditions for a FOR loop should not be explicitly stated in the code. Instead, the end conditions should be determined by the data or variables that are being used in the loop. This ensures that the loop will always terminate when the conditions are met, regardless of the data or variables used. This also makes the code more flexible and easier to maintain.
Key Benefits
- Avoid errors: By not hard-coding the end condition, you can avoid errors that occur when the condition is incorrectly set.
- Flexibility: This rule allows you to create a more flexible loop that can be adapted to changing conditions.
- Efficiency: By avoiding hard-coded end conditions, you can save time and resources when using the loop.
Non-compliant Code Example
BEGIN
<<ForLoopOnCustomer>>
FOR i IN 1 .. CUSTOMER_TABLE.COUNT --Non compliant code (For loop end conditions are hard-coded)
LOOP
IF CUSTOMER_TABLE(i) IS NOT NULL THEN
DBMS_OUTPUT.PUT( i || ' = (' || CUSTOMER_TABLE(i).Name || ', ' || CUSTOMER_TABLE(i).PhoneNumber || ')' );
ELSE
DBMS_OUTPUT.PUT( i || ' IS NULL' );
END IF;
END LOOP ForLoopOnCustomer;
COMMIT;
END;
Compliant Code Example
BEGIN
<<ForLoopOnCustomer>>
FOR i IN CUSTOMER_TABLE.FIRST .. CUSTOMER_TABLE.LAST --Compliant code
LOOP
IF CUSTOMER_TABLE(i) IS NOT NULL THEN
DBMS_OUTPUT.PUT( i || ' = (' || CUSTOMER_TABLE(i).Name || ', ' || CUSTOMER_TABLE(i).PhoneNumber || ')' );
ELSE
DBMS_OUTPUT.PUT( i || ' IS NULL' );
END IF;
END LOOP ForLoopOnCustomer;
COMMIT;
END;