Home
GOTO should not be used within loops
Description
The GOTO statement should not be used within loops in PL/SQL code. This is because it can cause unexpected behavior and can make the code difficult to read and maintain. Instead, use the EXIT statement to exit the loop, or use the CONTINUE statement to skip the rest of the loop and continue with the next iteration. This will help to ensure that the code is more readable and maintainable.
Key Benefits
- Easier to debug - GOTO statements make code harder to debug as it is difficult to trace the flow of the program.
- Easier to maintain - GOTO statements make code more difficult to maintain as it is difficult to trace the flow of the program.
- More efficient code - GOTO statements can often lead to inefficient code as it is difficult to optimize the flow of the program.
- More readable code - GOTO statements make code less readable as it is difficult to follow the flow of the program.
Non-compliant Code Example
DECLARE
num VARCHAR2(50);
counter PLS_INTEGER := 81;
BEGIN
FOR i in 2..ROUND(SQRT(counter)) LOOP
IF counter MOD i = 0 THEN
num := ' is not a prime number';
GOTO print_now; --Non compliant code (GOTO statement used in the loop)
END IF;
END LOOP;
num := ' is a prime number';
<<print_now>>
DBMS_OUTPUT.PUT_LINE(TO_CHAR(counter) || num);
END;
Compliant Code Example
DECLARE
num VARCHAR2(50);
counter PLS_INTEGER := 81;
BEGIN
FOR i in 2..ROUND(SQRT(counter)) LOOP --Compliant code (GOTO statement is not used in the loop)
IF counter MOD i = 0 THEN
num := ' is not a prime number';
DBMS_OUTPUT.PUT_LINE(TO_CHAR(counter) || num);
ELSE
num := ' is a prime number';
DBMS_OUTPUT.PUT_LINE(TO_CHAR(counter) || num);
END IF;
END LOOP;
END;