09
Thu, May
2 New Articles

Call-Back Processing: A Brief Introduction

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

Modify any procedure such that when it's called by a program, it calls another procedure to perform additional logic.

Let's look at the technique of call-back processing from the perspective of an RPG programming scenario where the technique might be applied: list processing. Suppose that we have a procedure (or even a called program) that we currently use to build a list of customers based on their name and (optionally) city. Multiple programs use this procedure. One day we get a request from the marketing department that this procedure be modified to also allow selection based on additional criteria, such as state, ZIP code, etc. How should we handle this request? A number of options are open to us, including these:

 

·        Add this additional functionality to the current procedure

·        Add logic to the calling program to subset the list returned

·        Clone the current procedure and add the required logic to the new version

 

If we respond by adding logic to the current procedure, we have not only complicated the logic, but undoubtedly slowed down processing for all those other users who do not require the capability. And of course, knowing the marketing department, this will be just the first of many features that they want added, so it will only get worse in the future. If we add logic to the calling program, we have not only complicated the logic, but we may well have to face the possibility of having to make the same decision in the future should another user need a similar feature. The alternative of cloning the procedure is also unattractive since it will result in duplication of logic and therefore require double maintenance should the database change in the future. So is there an approach that will minimize these pitfalls?

 

One alternative that you might consider is to modify the list-building procedure such that whenever it is called by the marketing program, it calls another procedure to perform the additional logic. Call-back processing is an effective approach to implementing this type of solution, and it will do so in a highly flexible manner that will minimize the requirement for future code changes.

 

The basic mechanism is very simple: We modify the current procedure to accept an additional parameter in the form of a procedure pointer. When it is called, in addition to its own selection logic, it uses this pointer to call a procedure to apply additional selection criteria. Since the original caller supplies that procedure, any other users that require this functionality in the future have only to code their own procedure logic and change the call to pass the procedure pointer. No change is required in the utility list builder. One other advantage to this approach is that if the additional logic is dependent upon data in the caller, there is no need for this to be passed as parameters; it can simply be accessed as global data by the procedure.

 

By the way, "playing" with code like this in debug mode is often the best way to understand what is going on. So that you can "play" as quickly as possible with the sample program, I have avoided using files and instead just used data stored within the program. 

 

Let's look at a very simple example of how all this works. We'll start with the list-building procedure LISTBUILD. To make it simpler for you to review the code, the prototype (A) is hard-coded in the procedure, although it should of course really be in a /COPY member. You will see that the prototype describes four parameters. The first is the array in which the results are to be returned. The second and third are the selection parameters representing the low and high values in the range of items required. Since additional selectivity is required, the fourth parameter (B) supplies the procedure pointer for the user's selection routine. Note that by adding Options(*NoPass) to this parameter, we could avoid having to recompile programs that do not require the extra selection mechanism. We would of course need to modify the logic so that if the parameter was not passed, we would not attempt to call the user procedure. Notice that the procedure's return value is a count of the number of entries added to the array.

 

At (C), you will find the prototype for the user procedure. Of particular interest is the parameter to the ExtProc keyword, which is not in quotations marks as you might normally expect it to be. The compiler interprets this as meaning that pUserProc is not the name of the procedure, but rather the name of a procedure pointer that will contain the address of the required procedure. In other words, it associates the procedure pointer passed to us as the fourth parameter with the function name UserSaysOK. Whenever this function is invoked, the user procedure will be called.

 

One quick point before we move on: This is one of the very rare occasions when we would not use /COPY for the prototype of UserSaysOK. Why? Because each program that supplies a value for the procedure pointer will have its own prototype and name for the routine. The only requirement is that it must have the same "shape" as this prototype in terms of the number and size of parameters and the definition of the return value. 

 

     H NoMain Option(*NoDebugIO : *SrcStmt)

 

     D values          DS

 

     D                               30a   Inz('001012023034045056067078089090')

 

     D                               30a   Inz('101112123134145156167178189190')

 

     D                               30a   Inz('901912923934945956967978989990')

 

     D   value                        3s 0 Overlay(values) Dim(30)

 

(A)  D listBuild       Pr             5i 0

 

     D   list                         3s 0 Dim(30)

 

     D   low                          3s 0

 

     D   high                         3s 0

 

(B)  D   pUserProc                     *   ProcPtr

 

     P listBuild       B                   Export

 

     D                 PI                  Like(count)

 

     D   list                         3s 0 Dim(30)

 

     D   low                               Like(list)

 

     D   high                              Like(list)

 

     D   pUserProc                     *   ProcPtr

 

     D count           S              5i 0

 

     D i               S              5u 0

 

     D candidate       S                   Like(list)

 

(C)  D UserSaysOK      Pr              n   ExtProc(pUserProc)

 

     D  candidate                          Like(list)

 

      /Free

 

       For i = 1 to %Elem(value);  // Loop through all values

 

                         

 

         candidate = value(i);  // Select current candidate value

 

                         

 

         // Check if the candidate value is in the required range               

 

         If candidate >= low And candidate <= high;

 

                         

 

(D)        If UserSaysOK(candidate);  // Call user procedure to validate

 

             count += 1;

 

             list(count) = candidate; // & store value in list if needed

 

           EndIf;

 

                         

 

         EndIf;

 

                        

 

       EndFor;

 

       Return count;

 

      /End-Free

 

     P listBuild       E   

 

The logic in the list builder is very simple, and I won't waste time describing it here except to point out that once the main logic has determined that an entry is a candidate (i.e., it is within range), then that candidate is passed to the user procedure for further evaluation. Since the user function returns an indicator, we can simply use it in an expression (D) and include the candidate in the results if the user procedure says it is OK to do so.

 

Time now to take a look at the user procedure used in the example. It is coded in program CALLBACKT and is named FilterList. As you can see, it is very simple. All it is doing is further filtering the candidate entries by checking to ensure that they represent an even number (F). If they meet this additional selection criteria, then the function returns *On to indicate that the candidate should be included in the result set.

 

       // Procedure filters candidates to include only even numbers

      P FilterList      B

 

      D                 PI              n

 

 (E)  D  candidate                          Like(list)

       /Free

 (F)    If %Rem(candidate: 2) = 0;  // Check if candidate number is even

          Return *On;

        Else;

          Return *Off;

        EndIf;

       /End-Free

      P FilterList      E

That is pretty much all there is to it. The only thing that remains is to briefly look at how the ListBuild procedure is invoked from the main line of CALLBACKT. This is shown at (H) in the program. The definition of the procedure pointer pFilterList is passed as the fourth parameter being shown at (G).  Notice that when defining the initialization value for the pointer, we can simply reference the name of the function's prototype. The alternative approach would have been to code Inz(%PAddr('FILTERLIST')), which achieves the same thing but just doesn't seem quite as elegant. 

 

(G)  D pFilterList     S               *   ProcPtr Inz(%PAddr(FilterList))

(H)    count = ListBuild( list: low: high: pFilterList);

 

If all this seems like a lot of work to you (it isn't, but let's just assume it is!), then think about this: Suppose that the marketing department strikes again and now needs to go from using one additional selection function to having a choice of three or four different ones. All we would have to do is to code the additional selection functions and add the logic needed to switch which procedure pointer we pass on the call to the list builder. Now isn't that a whole lot easier than the alternatives?

 

Have fun with this, and please let me know of any uses you find for it in your applications.

Jon Paris

Jon Paris's IBM midrange career started when he fell in love with the System/38 while working as a consultant. This love affair ultimately led him to joining IBM.

 

In 1987, Jon was hired by the IBM Toronto Laboratory to work on the S/36 and S/38 COBOL compilers. Subsequently, Jon became involved with the AS/400 and in particular COBOL/400.

 

In early 1989, Jon was transferred to the Languages Architecture and Planning Group, with particular responsibility for the COBOL and RPG languages. There, he played a major role in the definition of the new RPG IV language and in promoting its use with IBM Business Partners and users. He was also heavily involved in producing educational and other support materials and services related to other AS/400 programming languages and development tools, such as CODE/400 and VisualAge for RPG.

 

Jon left IBM in 1998 to focus on developing and delivering education focused on enhancing AS/400 and iSeries application development skills.

 

Jon is a frequent speaker at user group meetings and conferences around the world, and he holds a number of speaker excellence awards from COMMON.

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$0.00 Raised:
$

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: