26
Thu, Dec
0 New Articles

PRACTICAL ILE - ILE Subroutines to Sub-Procedures

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

Why Subroutines Cause Blindness

Editor's Note: This article is excerpted from chapter 7 of 21st Century RPG: /Free, ILE, and MVC, by David Shirey.

In OPM, subroutines are a handy way to encapsulate code and keep from having one big, ugly mess of mainline instructions.

Technically, in ILE and /Free, you can still use subroutines. The EXSR and whatnot are supported, so there is no problem there.

Nor are subroutines totally evil. Before ILE, they were the best tool you had to take a section of code out of the mainline logic of the BOP and put it in a little spot all its own. You could execute it multiple times in your program but only have the code out there once, and if it were properly named (not easy given the length restrictions), it could help improve the readability of the program as a whole.

But for all the good, there are a number of serious drawbacks to subroutines.

First, the subroutine was still part of the BOP, and if the same logic were required in several programs, it had to be inserted into each of those programs separately.

That is, it couldn’t be set up as a separate entity and called by a number of other programs.

In addition, if it were inserted in multiple programs, unless it were done via a/Copy, you could have minor variations in the code, which could affect the universality of the business rules the routine represented.

And, if you made changes to it, then even if it were in a copybook, you still had to compile all the programs that used that copybook.

Second, it couldn’t handle either local variables or parameters.

A subroutine’s use of global variables actually made it harder to follow how a particular data element was being used, because first it was here, on line 135, and then suddenly it dropped into line 5387 and probably other places as well.

The bottom line is: you should be using are sub-procedures, not subroutines. End of story.

Sub-Procedures

The idea behind a sub-procedure is simple: take some code lines that are doing a particular task, take them out of the mainline code, and put them in a little spot of their own. Very similar to subroutines. But there are some major differences.

First, sub-procedures can only be done in an ILE program. They cannot be done in OPM.

Second, sub-procedures are not delineated by the BEGSR/ENDSR tags, but by B and E (beginning and end) P-specs. More on P-specs in a minute or so (depending on how fast you read).

Third, and this is a big one, sub-procedures allow you to define local variables in between the B and E P-specs.

You do this using D-specs that are listed after the B P-spec. This way, you can define any variable you want and use it in the sub-procedure. But only in the sub-procedure. Local variables cannot be used in any other part of the program. They are strictly for the sub-procedure. In fact, you could even give them the names of global variables that are used other places in the program or repeat the names of local variables from other sub-procedures. I don’t recommend either of those options, but it’s doable.

I can’t tell you how important I think local variables are and how dangerous global variables are to good program structure.

Fourth, while subroutines are accessed by using the EXSR operator, sub-procedures are “called” by doing a prototype call (CALLP). Even within a given program.

You might think there is more work involved in doing a call rather than just an EXSR, but the truth is—well, actually I guess the truth is it is a bit more work. But only a bit. And it’s well worth it to have the other advantages.

And fifth, while subroutine code must exist in the program that is using it, a sub-procedure can actually be set up in a separate program (a service program) that is truly called into the calling program using the CALLP prototype call. Service programs are an incredibly useful entity, and we will talk more about them in a couple of chapters.

Sub-Procedure Inside a Program Example

Let’s start our ILE adventures by looking at a program that calls an embedded sub-procedure (that is, the sub-procedure is part of the program that uses it). The sub-procedure itself is very simple; it just validates a product number against a product master (MSPMP100). We will look at the whole mess, then break it down into its components for easy digestion. Give it a name to your own liking.

PRACTICAL ILE - ILE Subroutines to Sub-Procedures - Figure 1

Now let’s take that program apart and see what makes it tick. You should be able to detect hints of apricot and chocolate and ... but there I go again. Each person tastes something different, and I shouldn’t try to plant suggestions.

Because I am doing this as if you are on 5.4 rather than 7.x, some things are present that may not be if you are on a more recent release of the software. Like having the F-, D-, and other specs be positional, and then having to use /Free and /End-Free to segregate the /Free from the positional code. Or the need for the H-spec to ensure this is compiled as ILE (more on that later). Sorry about that, but many of us are still back in that old era. It should not stop you from doing ILE.

Oh, and by the way, I am listing the code first, and then under it putting the discussion of that code. I would have been confused about that myself. As you go thru this section, DON’T focus on the text description. Focus on the code, devour it with your eyes, think about what you see, experience its richness and vibrancy. The text description is just to give it context, to help clarify what you are seeing. But focus on the code itself.

PRACTICAL ILE - ILE Subroutines to Sub-Procedures - Figure 2

First, the H-spec. This is put in there because sub-procedures are an ILE construct. So they cannot be in a program that uses the default activation group (that is OPM). The H-spec makes sure that the program is compiled as ILE, but if the defaults in your compile command are set for that, then you would not need this H-spec. I am assuming you will compile this with CRTBNDRPG instead of CRTRPGMOD/CRTPGM.

PRACTICAL ILE - ILE Subroutines to Sub-Procedures - Figure 3

This is then followed by the F-specs for this program.

Note that I am using a product master file plus a display file, and I am going to be pretending that I am picking up data entry fields from the display and editing them against the product master file for validity.

Remember, if you are on 7.1, TR7 or higher, we could set these up as file control statements. But since I am doing this book from a 5.4 perspective, we will set them up as F-specs.

PRACTICAL ILE - ILE Subroutines to Sub-Procedures - Figure 4

Then come the D-specs. The global D-specs. We are still in our mainline program here; we haven’t gotten to the sub-procedure yet. Just be patient, and quiet ... very, very quiet. We don’t want to spook it.

There are two things here in the D-specs. The first is the prototype D-spec, the thing identified with the PR as the D-spec data type. This is required in the program D-specs, and it identifies what sub-procedures will be used (by the CALLP) in that program. The D-spec subfields under it for D01_PRDNO, MSG, and ERROR_FLAG are the data elements that are passed in when the sub-procedure is “called.” Please note that there is no EXTPGM keyword on the PR, because we are not calling an external program, just a sub-procedure in this program.

If you had more than one sub-procedure embedded in this program, then you would need a PR prototype D-spec for each one of those sub-procedures.

Below that are two more D-specs: ERROR_FLAG and MSG.

ERROR_FLAG is a global data element, and it is used in the sub-procedure but also in the program calling the sub-procedure. Our little snippet does not show the ERROR_FLAG being used, but if there were more calls to other sub-procedures, they would be contained within an IF statement checking to see whether or not the ERROR_FLAG were set.

MSG is also a global variable, just a message field that we will set if there is an error.

What is interesting is that both of these fields are defined under the PR D-spec. So why are we defining them here again? Have I screwed up, defined them twice, and so the compile will fail? Normally, that would be a very good guess indeed, but not tonight. They are there because even though I have “defined” them in the PR above, anything listed in a PR is not really defined. It has to exist somewhere else, and so I have defined the field in a second, normal D-spec. Why aren’t things in a PR really defined to the system as fields? You might as well ask why the earth is an oblate spheroid. Because. Just because that’s the way it is. Deal with it.

PRACTICAL ILE - ILE Subroutines to Sub-Procedures - Figure 5

This is the /Free code that calls the sub-procedure.

And it’s very simple. I set the ERROR_FLAG (a global variable) to 'N', then call the sub-procedure, and then end the program. If this were a real program, we would probably have more calls to other sub-procedures, each covered by an IF ERROR_FLAG clause, to edit each of the fields on the display file. Oh, I guess I did use the ERROR_FLAG, after all, to initialize it.

Note that the call to the sub-procedure VAL_PRDNO is actually a call, using CALLP (Call Prototype).

And notice that the three data fields mentioned (can’t really say defined) in the VAL_PRDNO PR are sent to the sub-procedure as parms separated by a colon and surrounded by parentheses.

Just as an interesting side note, if there were no parms being sent to the sub-procedure, then nothing would be listed under the PR line in the D-specs (although we would still need the PR itself), and nothing would be included in the parenthesis on the CALLP. However, the parenthesis would still be included; they would just be empty—().

Finally, the /end-Free delimiter needs to be set because when we define the sub-procedure (next step), we will use P-specs and D-specs, which are positional RPG, not /Free. Granted, in 7.1 TR7, we can make them /Free, but that is not the version of the operating system that this book is based on.

PRACTICAL ILE - ILE Subroutines to Sub-Procedures - Figure 6

The sub-procedure itself really starts with the P-spec that has a B in position 24. The two lines above that are just icing that I put in to make it easier to see. Note that even though I have come out of /Free (last statement on previous page), I can still use the double slash for comments. Pretty cool, eh?

Then we have D-specs for the sub-procedure. If you are on a release 6.1 or above, you can also include F-specs in here, so instead of defining the files at the global level, you can define them in the sub-procedure. (This is separate from the stuff in 7.1 TR7.) But we are at 5.4, so that option is not open to us.

Note that we have another D-spec that defines the prototype, but this one is a PI, which is called the procedure interface. So we have a PR in the program and a PI in the sub-procedure. Let’s replay that one more time. The PR is the prototype D- spec; the PI is the procedure interface D-spec. Try to remember that.

Then, we have one more D-spec for SP_PRDNO. Technically, this field is not necessary for the functioning of this module. I could have just as easily used the global variable D01_PRDNO from the display file, but I was so excited about local variables that I just had to define one. If you tried to use this local variable (SP_PRDNO) in the mainline code above, you would get a compile error saying the data element was undefined. But you can use it in the sub-procedure code below.

Please note that the PR and PI specs are D-specs. D-specs. The P-specs are just used to denote the start and finish of the sub-procedure as a whole.

PRACTICAL ILE - ILE Subroutines to Sub-Procedures - Figure 7

Finally, we are into the code for the sub-procedure. As you can see, we are going back to /Free here, and the code is very simple. Like subroutines, all the sub-procedures will be listed after the *INLR = '1' in the mainline logic.

Even though I don’t need it, I set the local variable equal to the value from the display file and used that to read the product master file. I could have just as easily used D01_PRDNO, which is a global variable, in the statement. There is no advantage to using the local variable here; I just wanted to showcase it. There are, however, advantages in general to using local variables.

If it doesn’t get a hit, I set the ERROR_FLAG to 'Y' and throw message verbiage into the MSG field. Both of these values (the parms) are returned and can be used in the mainline code. The only thing that can’t be used in the mainline is the local variable SP_PRDNO.

Finally, the very last line in the whole mess is another P-spec, this one with a E (for End). If there were other sub-procedures in the program, they would be listed below just as we list subroutines below each other at the very end of the program.

PRACTICAL ILE - ILE Subroutines to Sub-Procedures - Now Your Turn

One More Thing: Debug

There is one more thing that I should probably mention.

One of the best ways to get into these methods is to run debug through the programs. But if you are using STRDBG (Start Debug) in PDM, you may be surprised when the F10 sequencing skips right over the sub-procedure.

To step into the sub-procedure, you can either set a breakpoint within the sub-procedure and use F12 to get to it or else use F22 versus F10 when you are ready to step into the sub-procedure.


What You Shoulda Learned

Yes, it’s different from the way we do subroutines. Not completely different— there are some similarities, but different enough to be different.

But it’s not bad. I mean, it’s doable. Really pretty easily doable. And by the end of this episode, if you did the Now It’s Your Turn activity, you should know how to:

  • Learn about the differences between subroutines and sub-procedures.
  • Code up a sub-procedure that is used internally in a
  • Learn about the difference between global and local
  • Learn how to code up both the PR (prototype) D-spec, and the PI (procedure interface) D-spec.
  • Learn how to use the P-specs, both the B and E Also, make sure you are clear on the difference between the P-spec, and the D-specs that define the prototype, and the procedure interface—that is, the PR and the PI.

Take a minute and think how odd it is that to access the sub-procedure in the program you have to use a CALLP. But just a moment. And then smile, and say to yourself in a very calm voice, “But I think that’s nice.” If that doesn’t work, try a double bourbon straight up. Don’t sip.

Remember that this is an ILE program, so you must compile this program as ILE (that is, with the DFTACTGRP set to *NO and an ACTGRP specified in the compile). Otherwise you can expect some very weird errors in your compile. Including the H-spec will take care of this.

Even if you never go any further with ILE than doing this (using sub-procedures instead of subroutines), you will have made an important step forward in your professional development. But, of course, you will go further, especially after the subliminal messaging in this chapter kicks in. Oh, yes, you will go further.

Want to learn more?  You can pick up Dave Shirey's book, 21st Century RPG: /Free, ILE, and MVC, at the MC Press Bookstore Today!

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: