Collecting Common GO TOs

Suppose a piece of code always exits by one of several GO TOs, all of which have the same destination. For example:
 2100-PROCESS-RECORD.
*
     IF JK-WTN-REC
        PERFORM 2200-PROCESS-WTN
        GO TO 2100-EXIT
     ELSE IF JK-ORD-REC
        PERFORM 2700-PROCESS-ORD
        GO TO 2100-EXIT
     ELSE IF JK-HDR-REC
        PERFORM 2800-PROCESS-HDR
        GO TO 2100-EXIT
     ELSE IF JK-TLR-RECORD
        PERFORM 2850-PROCESS-TLR
        GO TO 2100-EXIT.
*
 2100-EXIT.
     EXIT.
Collect all these GO TOs into a single one at the end:
 2100-PROCESS-RECORD.
*
     IF JK-WTN-REC
        PERFORM 2200-PROCESS-WTN
     ELSE IF JK-ORD-REC
        PERFORM 2700-PROCESS-ORD
     ELSE IF JK-HDR-REC
        PERFORM 2800-PROCESS-HDR
     ELSE IF JK-TLR-RECORD
        PERFORM 2850-PROCESS-TLR.
*
     GO TO 2100-EXIT.
*
 2100-EXIT.
     EXIT.
This rearrangement reduces the sheer number of GO TOs. More importantly, it makes it easier to apply some other transformation to the remaining GO TO. In the example, depending on how the paragraph receives control, we can probably eliminate the GO TO entirely, along with the EXIT paragraph and one or more THRU clauses.

This transformation may apply not only to an entire paragraph but also to part of one. For example:

     IF JK-TLR-RECORD
        IF JK-TLR-COUNT = INPUT-COUNT
           PERFORM 2855-DISPLAY-INPUT-COUNT
           GO TO 2100-EXIT
        ELSE
           PERFORM 2860-REPORT-BAD-COUNT
           GO TO 2100-EXIT
     ELSE
*
* more code here
*
Regardless of the surrounding context, this fragment may become:
     IF JK-TLR-RECORD
        IF JK-TLR-COUNT = INPUT-COUNT
           PERFORM 2855-DISPLAY-INPUT-COUNT
        ELSE
           PERFORM 2860-REPORT-BAD-COUNT
        END-IF
        GO TO 2100-EXIT
     ELSE
*
* more code here
*
Besides eliminating a GO TO, this change simplifies the code a bit, making it easier to manage. For example, we can now extract the inner IF-ELSE into a separate paragraph and PERFORM it.

In the early stages of the rewrite you may not have many opportunities to collect common GO TOs. However you can often create opportunities by applying other transformations, and especially by letting GO TOs percolate upwards.


[style forum]COBOL Style Forum [spaghetti]Spaghetti code [stage]Next stage
[home]COBOL Home