Returning data structures from Procedures

This post stems from recent conversation on the subject of prototyped parameters. I always pass parameters as read only (using the const keyword) in order to ensure that no unexpected changes in the called procedure can impact the calling procedure.

With this approach, the only value you need to worry about is the value explicitly returned by the procedure and this enforced simplicity makes life much, much easier for whoever ends up maintaining the application.

But, my colleague wanted to know, what do you do if you want your procedure to return multiple values? It doesn’t make much sense, for example, to call a separate procedure for each line of a customer address.

The answer is to use a data structure.

As an example, here’s a main procedure that, among other things, retrieves a customer address. As should be clear, I am using a data structure (ADR) to hold the address and using the procedure getAddress to populate this data structure.

     p Main            b
     d Main            pi

     d ADR             ds                  qualified
     d  Street                       50a   inz
     d  House                         5s 0 inz
     d  Postcode                      4s 0 inz
     d  City                         50a   inz
      /free

        // Some loop reading customers
        // ...

            // Retrieve the customer address
            ADR = GetAddress(CustomerNumber);

            // Continue
            // ...


        return;

      /end-free
     p Main            e

And this is what the getAddress procedure looks like:

     p getAddress      b
     d getAddress      pi                  likeds(ADR)
     d  Customer                     10p 0

      
     d ADR             ds                  qualified
     d  Street                       50a   inz
     d  House                         5s 0 inz
     d  Postcode                      4s 0 inz
     d  City                         50a   inz
      /free


        // Populate the ADR fields
        ADR.Street = 'SomeStreet';
        ...

        // And return the data structure
        return ADR;

      /end-free
     p getHistory      e

As you can see, as long as the ADR data structure is locally defined in both procedures you can easily pass the contents of the data structure from one procedure to the other.

Footnote

I know I am using fixed format definitions here, but the box we were looking at while discussing this is only on 7.1.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.