05
Sun, May
6 New Articles

Practical RPG: Flexible Parameters, Part 2

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

As parameter lists get more complex, making parameters optional gets harder, but service programs can help.

 

This series is all about encapsulating your business logic. In the first article in this series, I showed you how to use optional parameters to make your called program a little more flexible. This technique works very well in simpler cases when you have just a few parameters and some are used less frequently than others. However, optional parameters become a bit more cumbersome when the number of parameters grows or when any combination of optional parameters can be passed. This article presents a different approach that can handle any variety of parameters.

Moving Away from Optional Parameters

Let's review our parameter list from last time.

 

d OrdExp       pi                                

d iOutputFile            128   varying      

d iNumOrders                6s 0

d iBegOrder                     like(OHORDNUM) options(*nopass)

d iEndOrder                     like(OHORDNUM) options(*nopass)

d iCustomer                     like(OHCUSNUM) options(*nopass)

 

d wBegOrder    s                  like(iBegOrder) inz(0)

d wEndOrder    s                  like(iEndOrder) inz(*hival)

d wCustomer    s                  like(iCustomer) inz(0)

 

/free                          

if %parms > 2;                

 wBegOrder = iBegOrder;      

 if %parms > 3;              

   wEndOrder = iEndOrder;    

   if %parms > 4;            

     wCustomer = iCustomer;  

   endif;                    

 endif;                      

endif;                        

 

If you recall, we took special care to order our parameters so that required input and returned parameters were first, followed by optional parameters. Then we created work variables for each of the input parameters with appropriate initial values, and finally we checked the number of parameters passed to determine whether to override the initial values with parameters passed in. While it is a nice concept, it does tend to be a little inflexible, and it also requires some setup work. That work grows as you add more parameters. Picture adding some new variables. Say we wanted to select only orders of a specific type, allow for selecting a specify state or zip code, and also add a yes/no flag to include only open orders. The parameter list would look like this:

 

d OrdExp       pi                                

d iOutputFile            128   varying      

d iNumOrders                6s 0

d iBegOrder                     like(OHORDNUM) options(*nopass)

d iEndOrder                     like(OHORDNUM) options(*nopass)

d iCustomer                     like(OHCUSNUM) options(*nopass)

d iType                         like(OHORDTYP) options(*nopass)

d iState                         like(OHSTATE) options(*nopass)

d iZipCode                       like(OHPSTCOD) options(*nopass)

d iOnlyOpen                  n                options(*nopass)

 

If you look at the parameter list, you'll notice that in order to specify zip code, I also have to specify state code, which is unnecessary. This isn't the only situation like this either; any mutually exclusive parameters get sort of ugly. There's no way to order them so that you only specify one or the other. Not to mention the fact that I have to add more work variables and extend my %parms test code. So that brings me to the next option: the service program.

Using a Service Program

What we're going to do is use a service program to provide multiple "wrappers" or interfaces to the called program, but with different parameter lists. In the object-oriented world, this sort of interface is called an "adapter" because that's exactly what it does: it adapts one parameter list to another. I'll write a service program that will have multiple procedures with only those parameters that make sense for that procedure. For example, ExportOrderRange might have beginning and ending orders, while ExportOpenCustomerOrders will need a customer number. Let's see how that works:

 

h nomain

 

d ORDHDR       e ds                template

 

d ExportOrderRange...                                                    

d               pr            6s 0 extproc('ExportOrderRange')        

d iOutputFile              128   varying                            

d iBegOrder                       like(OHORDNUM)                    

d iEndOrder                       like(OHORDNUM)                    

                                                                        

d ExportOpenCustomerOrders...                                           

d               pr            6s 0 extproc('ExportOpenCustomerOrders')

d iOutputFile              128   varying                            

d iCustomer                       like(OHCUSNUM) const                

                                                                        

d OrdExp       pr                 extpgm('ORDEXP')  

d iOutputFile              128   varying       const

d iNumOrders                6s 0                  

d iBegOrder                       like(OHORDNUM) const

d iEndOrder                       like(OHORDNUM) const

d iCustomer                       like(OHCUSNUM) const

d iType                           like(OHORDTYP) const

d iState                         like(OHSTATE) const

d iZipCode                       like(OHPSTCOD) const

d iOnlyOpen                    n                const

                                                        

p ExportOrderRange...                                   

p                b                   export            

d               pi            6s 0                    

d iOutputFile              128   varying       const    

d iBegOrder                       like(OHORDNUM) const    

d iEndOrder                       like(OHORDNUM) const    

                                                        

d wNumOrders   s             6s 0                    

                                                        

/free                                                  

OrdExp(iOutputFile: wNumOrders: iBegOrder: iEndOrder:  

       0: ' ': ' ': ' ': *off);                        

return wNumOrders;                                    

/end-free                                              

p                e                                      

                                                        

p ExportOpenCustomerOrders...                            

p                b                   export              

d               pi            6s 0                    

d iOutputFile              128   varying       const    

d iCustomer                       like(OHCUSNUM) const

                                                        

d wNumOrders   s             6s 0                    

                                                        

/free                                                  

OrdExp(iOutputFile: wNumOrders: 0: *hival: iCustomer:      

       ' ': ' ': ' ': *on);                            

return wNumOrders;                                    

/end-free                                              

p                e                                      

 

You'll see that the service program starts out with a NOMAIN statement as all service programs do. Next is a template used to bring in the field definitions of the ORDHDR file, which are used to define the various entries in the parameter lists.

 

Next is the prototype for the procedure ExportOrderRange. This procedure is designed specifically to export orders within a range of order numbers. Besides the order range, the only other field we need to pass is the export filename. So we define the procedure to take as input values the export file name and the beginning and ending order numbers. One thing you might notice is that the number of records has been transformed from an input/output parameter to the procedure return value. This is a standard technique that often allows you to use fewer temporary variables. If you only return one value, this is a good technique to use. The other common use for the return value is to return the completion code. Anything other than a successful completion and the caller can call another procedure to get more detailed information if needed. That topic is more appropriate in an article focused on service program design, so let's move on with this example.

 

You see another prototype in this case for the procedure ExportOpenCustomerOrders. It defines only the export filename and the customer number as input parameters. You may have noticed that I also specify an extproc keyword, which looks to be redundantly defining the procedure name. Don't be alarmed; that's working around an RPG convention. Traditionally, all names in RPG are uppercase, so when a procedure is exported, RPG converts the name to all uppercase. Being all spiffy and modern now, I prefer to use mixed case whenever possible, so I use the extproc keyword to override that behavior and export my procedure name in mixed case.

 

After the internal prototypes comes the prototype for the original RPG program that this service program will be calling. I don't have to use *NOPASS anymore, and I define all of the input parameters as constants with the CONST keyword. This allows me to pass them as literals in the procedures. Let's get on to those.

 

Take a look at ExportOrderRange. As already noted, the procedure takes three input parameters: the file name and the beginning and ending order numbers. Notice how the procedure passes those values through to the original program and then specifies default values for all the other parameters. That's what makes this whole technique work: the service program hides the complex parameter list from the calling program. You'll see something similar in ExportOpenCustomerOrders. In this case, the only parameter other than the export file name is the customer number. Everything else gets hardcoded during the call to OrdExp. Note that I am able to use *HIVAL to specify the ending order number as well as pass *ON into the iOnlyOpen parameter, directing the called program to include only open orders.

The Result

Here's how you write a program to call one of those procedures.

 

d ORDHDR       e ds                                                    

                                                                        

d ExportOpenCustomerOrders...                                            

d               pr            6s 0 extproc('ExportOpenCustomerOrders')

d iOutputFile             128   varying       const              

d iCustomer                       like(OHCUSNUM) const              

                                                                        

d wNumOrders   s             6s 0                                    

                                                                        

/free                                                                  

wNumOrders = ExportOpenCustomerOrders( 'yothere.com': 123456);        

*inlr = *on;                                                          

/end-free                                                              

 

As you can see, this program has no idea that the called program, ORDEXP, has nine parameters. As far as the program is concerned, it only passes in the output filename and the customer number, and one or both can even be literals. No messy work variables for unused parameters; the service program does all that for you.

 

Obviously, you can write as many of these procedures as makes sense. Just identify the most common combinations of parameters and call the procedure that way. And for unique circumstances, you can just prototype the ORDEXP program itself (using the same procedure found in the service program) and pass in all the variables. But the code above is simple, easy to read, and easy to maintain. Which is what we're looking for!

 

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

$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: