11
Fri, Oct
6 New Articles

Using Scope in Linear-Main Programs to Create More Stable Applications

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

Linear-main RPG programs eliminate the RPG logic cycle and add new levels of variable scoping to protect your code from bugs down the road.

While I am no expert in the RPG logic cycle, I have had to deal with it in older applications over the years. Most RPG developers have dealt with a logic cycle program at least once. I can honestly say I have never written a new logic cycle program, but I have seen others in the community doing it. This article is not intended to start a religious war about cycle programming. There are some who will never give it up. Instead, this article will demonstrate how to create a program without the logic cycle and concentrate on what I think is a very useful benefit to using linear-main procedures in program.

 

Variable Scoping

One of the biggest advantages of using subprocedures in RPG instead of subroutines is the ability to define variables, data structures, and even files locally within the subprocedure. Locally defined variables cannot be accessed or modified from outside of the subprocedure. This provides insulation from inadvertent effects from other parts of the program.

 

Ideally, a subprocedure will use only locally defined variables in its code. You can think of the subprocedure as a miniature program. It accepts and returns parameters and should be as self-contained as possible. However, a subprocedure can access and modify anything defined globally in the program; that is anything defined outside of a subprocedure. There are, of course, times when using globally defined elements is useful, but it should be the exception instead of the norm.

 

When writing a traditional RPG program, also known as a “cycle-main” program, your mainline code is coded at the global level. That means that any variables, data structures, or files needed in your mainline code must also be defined at a global level. This allows these elements to be open to manipulation from anywhere in the program. In very large programs, this allows unintended bugs to be introduced in the program from even very minor changes.

 

Our Example Program

To illustrate how global scoped variables can be dangerous, let’s look at a very simple RPG program.

 

       // global defines

       Dcl-S counter int(5);

 

       // mainline code

       For counter = 1 to 10;

         Dsply counter;

         My_Procedure();

       EndFor;

 

       *inLR = *On;

       Return;

 

       // subprocedures

       Dcl-Proc My_Procedure;

 

         // local defines

         Dcl-S counter int(5) ;

 

         For counter = 1 to 3;

           // Do Stuff

         EndFor;

 

       End-Proc;

 

As you can see, this program defines a counter variable that is used in the mainline of the code for a for loop. There is also a subprocedure called My_Procedure that has its own counter variable defined locally. This program will work just fine as coded. The program will output 1 through 10 on the screen as expected, because the counter variable in the subprocedure is scoped locally and is a completely different variable than the counter at the global level.

 

But what if I forgot to define counter in the subprocedure? What if I misspelled counter in the definition? Well, the program would compile without error because the field name exists globally. The program would also run, but I now have a bug. After displaying a 1, the program will get stuck in an infinite loop, outputting the number 5. Why? Because the for loop in the subprocedure will increment counter to 4 and exit. Then the mainline will increment counter to 5, display 5, and call the subprocedure. The subprocedure will loop around until counter equals 4 again, and the process repeats.

 

Take the code above and try it for yourself. If you comment out the local variable definition in My_Procedure, you will see what I mean. This is a simplified illustration of the way many bugs find their way into our code. Counters are just one example. I find most developers use a standard set of counter variables in their programs. Some use the name “counter.” Others like to use x, y, and z. It’s all just preference. It is easy to see from the example above how counters can get you in trouble, but counters aren’t the only types of variables that can be manipulated unintentionally. Any variable at the global level can be problematic, and identifying those types of bugs is not always as easy as spotting an infinite loop.

 

Creating a Linear-Main Program

So how can we protect our mainline code and variables from outside interference? The answer is simple. By using the MAIN keyword on the control spec, we can specify a subprocedure to be used as the mainline code for the program.

 

       Ctl-Opt Main(Main);

 

       // global defines

 

 

       Dcl-Proc Main;

         // local defines

         Dcl-S counter int(5);

 

         // mainline code

         For counter = 1 to 10;

           Dsply counter;

           My_Procedure();

         EndFor;

 

         Return;

       End-Proc;

 

       // subprocedures

       Dcl-Proc My_Procedure;

 

         // local defines

         Dcl-S counter int(5) ;

 

         For counter = 1 to 3;

           // Do Stuff

         EndFor;

 

       End-Proc;

 

Notice the Ctl-Opt keyword with the MAIN attribute set to Main. I always name my linear-main procedure Main for consistency. This is also the convention used in other languages, such as C/C++ and Java, so it should seem familiar to developers familiar with those languages.

 

Also note that I simply wrapped the declaration of counter and my mainline code with the declaration of my Main subprocedure. This defines my counter variable locally in my subprocedure. Now no matter what happens in My_Procedure, the counter variable cannot be affected. I can now be assured that my mainline code and its variables are isolated from any other part of the program unless explicitly passed into other subprocedures as a parameter.

 

If I do want a variable or data structure to be defined globally, I can still define it outside of the Main subprocedure, but I would do so only if I had a specific requirement for it. In general, I avoid globally defined elements if at all possible.

 

The last change you will notice is the removal of *inLR = *On. When you define a linear-main program, the RPG logic cycle is not included in the program. The last record indicator has no meaning.

 

This brings up an important note. Because the RPG cycle is not included in the program, there are some distinct differences with regard to globally defined elements. Globally defined files must be explicitly closed. A globally defined file will be opened automatically on the first call of the program, but it will not be closed automatically. It will also not be reopened automatically on subsequent calls. Globally defined variables and data structures will be initialized only on the first call of the program. They will not be reinitialized on subsequent calls as they would when an RPG cycle program ends with *inLR=*On.

 

Final Thoughts

As you can see, the setup of a linear-main program is actually quite simple. There are definitely advantages to doing so. Variable scoping is only one example. There are of course differences in programs when you eliminate the RPG cycle, and this can be a bit of an adjustment for long-time RPGers. Change is not a bad thing, and I encourage you to give linear-main programs a try. I write all of my new programs this way and have not missed the cycle at all.

 

It is important that we as developers strive to learn new things. What I’ve shown you is something that can be learned very easily and can have real benefits in your applications. Now get started!

 

Brian May

Brian May, an IBM Power Systems Champion and Solutions Architect for Profound Logic Software, devotes the majority of his time to assisting customers with their modernization efforts. He frequently writes and speaks on topics related to RPG, JavaScript, and IBM i Modernization. Brian recently contributed his time and expertise to the new IBM i Modernization Redbook.

 

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: