Methods in COBOL

COBOL supports structured programming with divisions, sections, and paragraphs. While it doesn’t have methods in the same way as object-oriented languages, we can use paragraphs to organize our code in a similar manner.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. RECTANGLE-CALCULATIONS.

       ENVIRONMENT DIVISION.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 RECTANGLE.
          05 WIDTH  PIC 9(4).
          05 HEIGHT PIC 9(4).
       01 RESULT    PIC 9(8).

       PROCEDURE DIVISION.
       MAIN-PROCEDURE.
           MOVE 10 TO WIDTH OF RECTANGLE
           MOVE 5 TO HEIGHT OF RECTANGLE

           PERFORM CALCULATE-AREA
           DISPLAY "AREA: " RESULT

           PERFORM CALCULATE-PERIMETER
           DISPLAY "PERIMETER: " RESULT

           STOP RUN.

       CALCULATE-AREA.
           COMPUTE RESULT = WIDTH OF RECTANGLE * HEIGHT OF RECTANGLE.

       CALCULATE-PERIMETER.
           COMPUTE RESULT = 2 * (WIDTH OF RECTANGLE + HEIGHT OF RECTANGLE).

In this COBOL program, we define a structure called RECTANGLE with WIDTH and HEIGHT fields. We then create two paragraphs, CALCULATE-AREA and CALCULATE-PERIMETER, which perform calculations similar to the methods in the original example.

The MAIN-PROCEDURE sets up a rectangle with width 10 and height 5, then calls each calculation paragraph and displays the results.

To run this COBOL program, you would typically compile it and then execute the resulting binary. The exact commands may vary depending on your COBOL compiler, but it might look something like this:

$ cobc -x rectangle-calculations.cob
$ ./rectangle-calculations
AREA: 00000050
PERIMETER: 00000030

COBOL doesn’t have pointers in the same way as some other languages, so the distinction between value and pointer receivers doesn’t apply. Instead, COBOL uses a pass-by-reference mechanism for its procedure calls, which means that the RECTANGLE structure is effectively shared across the entire program.

While COBOL’s approach is quite different from object-oriented languages, it can still achieve similar results in terms of organizing code and performing calculations on data structures.