Name

LOOP-02: Make the termination conditions of a loop obvious

Synopsis

Loop logic is easier to determine if all the control logic is in one place, either in the WHILE or UNTIL clauses or in a LEAVE statement within the loop. It’s particularly confusing to include a RETURN statement within a loop.

To that end, we suggest that you avoid LEAVE or RETURN statements within WHILE or REPEAT UNTIL loops.

Example

In the following example, borrowed from the prime number routine in the preceding section, a WHILE loop contains a LEAVE clause—there are two ways for the loop to terminate, and this makes the code harder to analyze and trace:

    SET j=2;
    SET is_prime=1;
    divisors: WHILE(j< i) DO
      IF MOD(i,j)=0 THEN
        SET is_prime=0;
        LEAVE divisors;
      END IF;
      SET j=j+1;
    END WHILE;

One way to improve the readability of the loop would be to move all of the termination logic into the WHILE clause:

    SET j=2;
    SET is_prime=1;
    divisors: WHILE(j< i AND is_prime=1) DO
      IF MOD(i,j)=0 THEN
        SET is_prime=0;
      END IF;
      SET j=j+1;
    END WHILE;

Alternatively, we could employ a simple loop and place all termination logic within the loop.

Get MySQL Stored Procedure Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.