Multiple Entries into Loops

Probably the ugliest kind of loop is one with multiple entries. It behaves differently depending on where you enter. If you try to clean up one of its behaviors, you're likely to disrupt another one.

Since each entry point requires a separate paragraph label, you can't confine the loop to a single paragraph. Hence you can't rearrange it into a Standard Canonical Loop.

For example, consider these two GO TOs, which enter the same loop at two different places:

     PERFORM 3900-GET-FIRST-RECORD.
     GO TO 3110-PROCESS-RECORD. -------------------+
     ...                                           |
     GO TO 3100-GET-NEXT-RECORD. -----------+      |
     ...                                    |      |
*                                           |      |
 3100-GET-NEXT-RECORD. <---------------+ <--+      |
*    do some stuff (no GO TOs)         |           |
     GO TO 3110-PROCESS-RECORD. --+    |           |
*                                 |    |           |
 3110-PROCESS-RECORD.  <----------+ <--|-----------+
*    do some other stuff (no GO TOs)   |
     IF NOT END-OF-FILE                |
        GO TO 3100-GET-NEXT-RECORD ----+
     ELSE
        GO TO 3999-EXIT.---------------+
*                                      |
 3999-EXIT.  <-------------------------+
     EXIT.
This code is almost a Standard Canonical Loop -- except for that first GO TO, which jumps into the middle.

There are two ways to tame such a beast:

  1. Merge the entry points into one.
  2. Retain the separate entries but replicate the rest of the loop, one replica for each entry. Then work on each replica separately.

Pros and Cons

In this example, we can merge the entry points in a few simple steps and quickly obtain a single loop. Replicating the loops works, too, but it results in two loops instead of one. It takes more work to eliminate this duplication.

If the original code were more complicated, however, it may be impossible to find a simple way to merge the entry points. Replication may be more tedious, and may lead to duplication of code, but it always works.

Conclusion: Merge when you can, and replicate when you must.


[home]Cobol Home [style forum]Cobol Style Forum [spaghetti]Spaghetti code