27
Wed, Nov
0 New Articles

Practical RPG: Using Callbacks to Reduce Complexity

RPG
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

You may have heard of callbacks or even seen some abstract examples, but this article shows you how to use them to be more productive.

 

 

The concept of a callback procedure is unusual for us RPG programmers, to say the least--especially for those of us who have come from the monolithic programming architectures of the early midranges and embraced the hipper, cooler concept of called programs and the brave new world of procedures. While it's easy to get my head around a procedure by thinking of it as a subroutine with parameters (thus seeing the immediate benefit of that concept), the notion of a callback is a bit more complex, mainly because the benefit of the approach is not immediately obvious. This article offers a practical example of how to use callbacks to make development much easier.

Callbacks Reduce Complexity

It's as simple as that. One of the best uses of callbacks is to reduce or hide complex code. And the best example of complex code that needs hiding is the interface between applications and the operating system--that bizarre alternate programming world known as the IBM APIs.

 

If you've ever used APIs, you know two things: they are very powerful, and they are an absolute pain to program. Whether it's the old, crusty API definitions (using type B fields in the data structures) or the confusion of using pointers to structures containing pointers to other structures, using even one of the easier APIs like QUSLSPL (List Spooled Files) can turn a simple program into a hard-to-read mess. In the specific case of QUSLSPL, the mess comes from a couple of different points, both of which are common when dealing with IBM APIs. One point is that this particular API uses user spaces to return information. This is common, especially among older APIs. (Many of the newer APIs use the more powerful but potentially even more confusing Open List APIs, which have been demystified in MC Press Online articles by Bruce Vining; see his article on finding service programs for an introduction.) The other confusing bit is the general clutter of data structures that come about when using APIs. Even though you can limit the mess to some degree by using copy books, you still end up with dozens and dozens of variables defined in your program, many of which you won't even use. This was less of an issue in the days before WDSC and RDi, but now having all those variables can reduce the usefulness of the content assist capabilities of the tool; when you're trying to find a variable, all those data structure subfields show up as well.

 

 

Let's take a look at one of the simpler APIs, the List Spooled Files API, QUSLSPL. The following program takes two parameters, the output queue name and output queue library, and then displays a list of spooled files in that output queue. This is an example program, so all I do is display the spooled files using the DSPLY opcode.

 

 

A    h option(*srcstmt:*nodebugio)

B     // Basic error structure

B     //  Causes errors to raise exceptions

B    d dsDftErr        ds

B    d  BytesProvided                10i 0 inz(0)

B    d  BytesAvail                   10i 0 inz(0)

C     // User Space routines

C    d UserSpace       C                   'PRA100    QTEMP'

C    d QUSCRTUS        pr                  extpgm('QUSCRTUS')

C    d   UsrSpcNam                   20    const

C    d   Attribute                   10    const

C    d   Size                        10i 0 const

C    d   InitValue                    1    const

C    d   Authority                   10    const

C    d   Text                        50    const

C    d   Replace                     10    const

C    d   Error                             like(dsDftErr)

C    d QUSPTRUS        pr                  extpgm('QUSPTRUS')

C    d   UsrSpcNam                   20    const

C    d   Pointer                       *

C    d   Error                             like(dsDftErr)C

C    d ListHeader      ds                  based(pListHeader)

C    d   GenericHdr                 124a

C    d   ListOffset                  10i 0

C    d   ListSize                    10i 0

C    d   NumEntries                  10i 0

C    d   EntrySize                   10i 0

C    d QUSDLTUS        pr                  extpgm('QUSDLTUS')

C    d   UsrSpcNam                   20    const

C    d   Error                             like(dsDftErr)

D     // QUSLSPL processing

D    d QUSLSPL         pr                  extpgm('QUSLSPL')

D    d   UsrSpcNam                   20    const

D    d   Format                       8    const

D    d   UserID                      10    const

D    d   QualOutq                    20    const

D    d   FormType                    10    const

D    d   UserData                    10    const

D    d   Error                             like(dsDftErr)

D    d SPLF0300        ds                  based(pSPLF0300)

D    d  JobName                      10a

D    d  UserID                       10a

D    d  JobNumber                     6a

D    d  SplfName                     10a

D    d  SplfNumber                   10i 0

E     // Mainline prototype

E    d PRA100          pr                  extpgm('PRA100')

E    d   iQName                      10a

E    d   iQLib                       10a

E    d PRA100          pi

E    d   iQname                      10a

E    d   iQLib                       10a

F    d msg             s             50a

C    d i               s             20i 0

      /free

C      // Create user space and retrieve it

C      QUSCRTUS  ( UserSpace : 'TEST': 4000000: x'00': '*ALL':

C                  'Spooled Files': '*YES': dsDftErr );

C      QUSPTRUS  ( UserSpace : pListHeader: dsDftErr );

D      // Populate User Space with spooled files

D      QUSLSPL   ( UserSpace: 'SPLF0300': '*ALL': iQName+iQLib:

D                  '*ALL': '*ALL': dsDftErr );

C      // Position pointer to first entry in list

C      pSPLF0300 = pListHeader + ListOffset;

C      // Process entries

C      for i = 1 to NumEntries;

F        msg = %trim(Jobname) + '/' + %trim(UserID) + '/' + JobNumber +

F              '-' + %trim(SPlfName) + '.' + %char(SplfNumber);

F        dsply msg;

C        pSPLF0300 += EntrySize;

C      endfor;

C      QUSDLTUS  ( UserSpace: dsDftErr );

E      *inlr = *on;

      /end-free .

 

 

 

 

This article won't be an in-depth treatise on the APIs themselves; I hope I can do some of that in other articles. Today's article is going to focus on how to separate the application logic from the API support programming. In the program above, nearly all of the programming is API support programming. Let me address the pieces:

 

 

A)    Header specification for creating the program (sort of standard)

B)    Data structure used for processing errors (standard for all APIs)

C)    Support programming for the user spaces APIs

D)    Support programming for the spooled file list API

E)     Program infrastructure (parms and so on)

F)     Finally, the actual application code

 

 

 

 

Note that I'm using "ILE concepts" even in this example. I've replaced the *ENTRY PLIST with a prototype and procedure interface (that's the bulk of the code in section E). It's a little extra code, but I find that by forcing myself to use prototypes even for the main procedure's parameters, I continue to reinforce my use of prototypes everywhere (not to mention the fact that it's really easy to copy that prototype into another program and use it in a free-form call).

 

 

Sure, you can use a bunch of copy books to reduce this code, but you're still going to have a whole lot of complexity that just doesn't need to be there. What's even worse is that each time you need slight differences in the processing (selecting only spooled files for a specific job or only those with a specific status), you'll have to clone this code and make minor modifications, which in turn means having to remember exactly how all this code works.

 

 

One way around it would be to create an array of the SPLF0300 data structures and pass that to a program that encapsulates the API support logic. It's not a bad approach really, and it has a number of advantages, the most obvious being that you don't need to use procedures of any kind (and thus don't have to mess with ILE concepts). But trust me; if you don't already have procedures in your toolbelt, they should be one of the first tools you add, and besides, passing arrays has one built-in problem: array sizes. Since arrays in RPG have a fixed size, either you have to make the array large enough to handle the largest possible number of entries or you have to also pass a "more entries" flag and call the API repeatedly. Once you've done the latter, you might as well just call the program and get back one entry at a time, and once you've gone down that road, callbacks begin to be a much more attractive approach.

Implementing Callbacks

Instead of having one program, what we do is sever the application code cleanly from the API support code, using the magic of the callback routine. Let's take a look at the two new programs. The first program, PRA101, encapsulates all of the API processing logic in PRA100:

 

 

A    h dftactgrp(*no) actgrp(*caller) option(*srcstmt:*nodebugio)

B     // Basic error structure

B     //  Causes errors to raise exceptions

B    d dsDftErr        ds

B    d  BytesProvided                10i 0 inz(0)

B    d  BytesAvail                   10i 0 inz(0)

C     // User Space routines

C    d UserSpace       C                   'PRA100    QTEMP'

C    d QUSCRTUS        pr                  extpgm('QUSCRTUS')

C    d   UsrSpcNam                   20    const

C    d   Attribute                   10    const

C    d   Size                        10i 0 const

C    d   InitValue                    1    const

C    d   Authority                   10    const

C    d   Text                        50    const

C    d   Replace                     10    const

C    d   Error                             like(dsDftErr)

C    d QUSPTRUS        pr                  extpgm('QUSPTRUS')

C    d   UsrSpcNam                   20    const

C    d   Pointer                       *

C    d   Error                             like(dsDftErr)

C    d ListHeader      ds                  based(pListHeader)

C    d   GenericHdr                 124a

C    d   ListOffset                  10i 0

C    d   ListSize                    10i 0

C    d   NumEntries                  10i 0

C    d   EntrySize                   10i 0

C    d QUSDLTUS        pr                  extpgm('QUSDLTUS')

C    d   UsrSpcNam                   20    const

C    d   Error                             like(dsDftErr)

D     // QUSLSPL processing

D    d QUSLSPL         pr                  extpgm('QUSLSPL')

D    d   UsrSpcNam                   20    const

D    d   Format                       8    const

D    d   UserID                      10    const

D    d   QualOutq                    20    const

D    d   FormType                    10    const

D    d   UserData                    10    const

D    d   Error                             like(dsDftErr)

D    d pSPLF0300       s               *

E    d PRA101          pr                  extpgm('PRA101')

E    d   iQName                      10a   const

E    d   iQLib                       10a   const

G    d   iCallback                     *   const procptr

E    d PRA101          pi

E    d   iQName                      10a   const

E    d   iQLib                       10a   const

G    d   iCallback                     *   const procptr

G    d Callback        pr                  extproc(pCallback)

G    d   pSPLF0300                     *   value

G    d pCallback       s               *   procptr

E    d i               s             20i 0

      /free

G      // Save callback pointer

G      pCallback = iCallback;

C      // Create user space and retrieve it

C      QUSCRTUS  ( UserSpace : 'TEST': 4000000: x'00': '*ALL':

C                  'Spooled Files': '*YES': dsDftErr );

C      QUSPTRUS  ( UserSpace : pListHeader: dsDftErr );

D      // Populate User Space with spooled files

D      QUSLSPL   ( UserSpace: 'SPLF0300': '*ALL': iQName+iQLib:

                   '*ALL': '*ALL': dsDftErr );

C      // Position pointer to first entry in list

C      pSPLF0300 = pListHeader + ListOffset;

C      // Process entries

C      for i = 1 to NumEntries;

G        Callback(pSPLF0300);

C        pSPLF0300 += EntrySize;

C      endfor;

C      QUSDLTUS  ( UserSpace: dsDftErr );

E      *inlr = *on;

      /end-free

 

 

 

 

You can go through the code line by line, but the differences between this program and the original are small and focused. New code is marked with the letter G in the leftmost column. This program does no application work and instead is passed one additional parameter in its main procedure interface. The parameter is the one named iCallback, and it is a variable of type pointer--more specifically, a procedure pointer (the asterisk in the data type indicates only a pointer of some type; the keyword procptr is what identifies the variable as a procedure pointer).

 

 

Immediately after that, a few more lines of code appear that define the prototype of the callback procedure (which I rather uncreatively named Callback). This prototype must be the same in both this program and the calling program, which I'll show you in a moment. Note, though, that the procedure is prototyped using the keyword extpgm(pCallback). This is the syntax that allows the calling program to pass the address of one of its procedures and then let the called program invoke that procedure. When I set pCallback equal to the value in the parameter iCallback, I am allowing PRA101 to call a procedure in the program that called PRA101. This is the essence of the callback concept.

 

 

Two other changes, then. First, you may notice that I don't even define the SPLF0300 data structure in this program. Since in this particular case the task of the called program is simply to return the data to the caller, it doesn't even need to examine the contents of the data and so has no need to define it. This doesn't happen all the time (instead the API support program sometimes needs to access the list entries--for example, to test values for selection purposes), but I thought I'd use this example to show that the separation of application and API support can even make the API support programming a little less complicated.


And finally, the loop near the end of the program: you'll see only one line of program infrastructure code, the actual call to the callback procedure passing the pointer to the list entry. And how is this handled in the calling program? Let's take a look at that:

 

 

A    h dftactgrp(*no) actgrp(*new) option(*srcstmt:*nodebugio)

D     // SPLF0300 Layout

D    d SPLF0300        ds                  based(pSPLF0300)

D    d  JobName                      10a

D    d  UserID                       10a

D    d  JobNumber                     6a

D    d  SplfName                     10a

D    d  SplfNumber                   10i 0

G    d Callback        pr

G    d  ipSPLF0300                     *   value

G    d PRA101          pr                  extpgm('PRA101')

G    d   QName                       10a   const

G    d   QLib                        10a   const

G    d   pCallback                     *   const procptr

E     // Mainline prototype

E    d PRA102          pr                  extpgm('PRA102')

E    d   iQName                      10a

E    d   iQLib                       10a

E    d PRA102          pi

E    d   iQname                      10a

E    d   iQLib                       10a

      /free

G      PRA101( iQName: iQLib: %paddr(Callback));

E      *inlr = *on;

      /end-free

G    p Callback        b

G    d                 pi

G    d  ipSPLF0300                     *   value

F    d msg             s             50a

      /free

G      pSPLF0300 = ipSPLF0300;

F      msg = %trim(Jobname) + '/' + %trim(UserID) + '/' + JobNumber +

F            '-' + %trim(SPlfName) + '.' + %char(SplfNumber);

F      dsply msg;

      /end-free

G    p                 e

 

 

 

 

As you can see, the calling program, PRA102, has almost no API support programming whatsoever. The little it has is the definition of the spooled file information data structure as defined by the QUSLSPL API. About 10 lines of code are used to create the callback procedure and its prototype, as well as to define the prototype to the PRA101 program and to call it in the mainline. It's interesting to note that the mainline in this case becomes exactly two lines: call the API support program and then end the program. As you know now, of course, the API support program processes the API request and repeatedly calls the callback routine, but all of that is shielded from the API programmer. While in this case the amount of code for the API support interface is relatively large compared to the application program itself, in a more sophisticated application the ability to add API support with just a dozen lines instead of a hundred begins to multiply, especially as you add more APIs.

This Is Just the Beginning

This is a relatively simple example.  In it, I only looped through the information returned from the QUSLSPL API and returned it directly to the program. In reality, I've found that I often have to call the QUSRSPLA API to obtain more information about the spooled file; that complexity could be hidden here as well.

 

 

In fact, one thing I want you to think about is that it would be easy to have many different callback prototypes; this would allow the same API support program to return different kinds of data, depending on what the application needs. The application program would simply pass the address of a callback procedure with different parameters and some sort of opcode to tell the API support program what to return. For example, the API support program could pass back a pointer to the SPLA0100 data structure, which contains much more information about the spooled file. I hope I can show you more about how that architecture would work in another article.

 

 

More important, though, is that this basic concept of hiding the complexity of the API support programming can be used for any of the IBM APIs. I've written wrappers for spooled files, object lists, members lists, you name it. And as you get the hang of it, you can expand the technique to your own application logic to return lists of invoices or inventory, hiding the complexity of that particular access from your programmers. Not only that, but it promotes the idea of reusable business logic, where changes to the business rules need only be made in one place.

 

 

Callbacks are a powerful programming technique and a great thing to add to your practical RPG toolbelt.

Joe Pluta

Joe Pluta is the founder and chief architect of Pluta Brothers Design, Inc. He has been extending the IBM midrange since the days of the IBM System/3. Joe uses WebSphere extensively, especially as the base for PSC/400, the only product that can move your legacy systems to the Web using simple green-screen commands. He has written several books, including Developing Web 2.0 Applications with EGL for IBM i, E-Deployment: The Fastest Path to the Web, Eclipse: Step by Step, and WDSC: Step by Step. Joe performs onsite mentoring and speaks at user groups around the country. You can reach him at This email address is being protected from spambots. You need JavaScript enabled to view it..


MC Press books written by Joe Pluta available now on the MC Press Bookstore.

Developing Web 2.0 Applications with EGL for IBM i Developing Web 2.0 Applications with EGL for IBM i
Joe Pluta introduces you to EGL Rich UI and IBM’s Rational Developer for the IBM i platform.
List Price $39.95

Now On Sale

WDSC: Step by Step WDSC: Step by Step
Discover incredibly powerful WDSC with this easy-to-understand yet thorough introduction.
List Price $74.95

Now On Sale

Eclipse: Step by Step Eclipse: Step by Step
Quickly get up to speed and productivity using Eclipse.
List Price $59.00

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: