Shift Happens - Write Beautiful Code

Shift Happens - Write Beautiful Code

Author's note: I wrote this article specifically for the RPG Unleashed website at www.ile-rpg.org. There is so much room for modern DB2 and RPG-ILE based development in the enterprise. I want to personally write beautiful code for successful applications that make companies profitable and the users empowered to take the businesses to new heights.

Please visit us at RPG Unleashed and take a look at some of the excellent articles and conversations that are happening there. Modernization and the sustainability of the IBM i platform starts with us, the developers. Let's write beautiful code.

The Coding Blocks podcast is easily found on iTunes and Sticher and their website is at CodingBlocks.

Shift Happens: 2 – Write Beautiful Code

Can RPG be beautiful? 

Can it just by observation look to the beholder as art, crafted as something elegant, spaced and phrased as beautiful poetry full of meaning and long lasting value?  Can RPG code speak of technical prowess and sophisticated logic? Can it look to the beholder as Einstein’s’ or other physicist’s equations look on a university blackboard?  Is this too much to ask for a 50-year-old computer programming language derived from punch cards and beholden for many years by folks in thick black glasses, pocket protectors, black ties, and green bar line fed printouts to be beautiful?

No, because that’s not what it is now. RPG, or as it should be called now ILE RPG, is a sophisticated and transformed software development language that is geared to run on huge data sets and transaction processing tasks to deliver cutting edge information transfer with extreme accuracy and 99.999999% online uptime. With some Googling it is completely possible to follow the language through its various shifts in the development sphere. It has simply has come a long way baby.

Clean Code

I have a long commute to work each way to work and try to make the most of my windshield time listening to audio books and podcasts.  One podcast I particularly enjoy is Coding Blocks which is hosted by three Dot Net developers who are fun guys and tackle topics that can relate to anyone who cuts code for a living.  Recently they have been doing a series on the book “Clean Code”.  They are taking a chapter at a time and are diving through what it takes to write clean, readable, and long lasting code. 

Does it matter about your spacing, using caps, consistent indents, white space, and how you comment? Yes, if you would like the code that you took the time to write to last over time and modifications?  In their world (the podcaster team) it matters significantly. They work on projects that have wave and wave of continued updates occurring as their websites grow and change. Many developers working in a decentralized online work environment check out and contribute code through a GIT-repository.  With this rapid development life cycle it is uber important to have clean code, built to style and standard, and understandable by many eyes and brains.

Your code should not look like a cross between doodle pad and a community bulletin board.  The code should express the idea of what is occurring right at that moment.  What is in a name, everything!  If you can name it, name it wisely so that it has a chance to live on and be understood. Pay attention to white space and how your syntax is spaced and understood to the eye.

May the Source Be with You

Let us take a look at some source for a short but useful ILE RPG program.  This is a program which is called from an external interface to retrieve and populate values used by an admin group who oversees credit responsibilities for a collection team.  Credit and collects is not very sexy, but the code in this small piece of the entire application can be beautiful in its own right.  Also, this needs to be said prior to working with this code, this is a smack dab right in the middle ILE RPG program that is neither on the cutting edge nor cast in columns like Roman artifacts, but is a great starting place for most RPG programmers as they start writing beautiful code.  One last thing, this code is from a machine that is on V7R1 but not on the latest technology refresh, so complete free form coding was not available.

The files and other potentially confidential and private information have been replaced with other values.

This is not the most beautiful code I have ever written but does have some of the basic building blocks of beautiful code that will be building on as I continue in this series and in others.  Let’s just take a snapshot of the code and then break it down into a couple of things.

The Heading:

If your shop does not use standardized headings for all development, why not start today?  This program has a very understated heading. The dark and dirty details of the application that this program is a simple module of is documented elsewhere in project documentation and specs, and the finished application in a development wiki.  This is indexed and searchable and a better place for the detail really needed for an application.  The programs heading just serves as a starting place to answer the who, what, where, and when the program came into place. 

I have read through War and Peace headings and all that effort and text becomes buried over time and irrelevant.  It is nice, but won’t last and is also not the best place for documenting a program. There are lots of tools for systems documentation, use those, not your heading, but by all means, include a heading, keep the asterisks to a minimum, and turn your CAPS LOCK OFF.

H-Specs:

Our change management software (please tell me you are using change management software) handles the majority of our object building tasks on promotions and deployments, but we include these three lines in our H specs to fit the requirements for the applications environment we run in.  The H specs of modern ILE RPG contain some very powerful tools for controlling how your source will compile, the formats of data within your program, handles default settings, and a few other things I should brush up on.

Files:

This is a simple program, and many times if best suited I will stick to pure SQL to achieve all the inbound and outbound data tasks.  In this program there may be data already in the table being used in the user interface, so to keep things simple, I have one file set for additions and updates. You may have some type of database data error handling like PSSR routines, etc.… What you put here should be standardized based on the world you work in, but keep it simple and direct.

Headings and Comments:

Comments are over-rated but necessary.  We have a standard of trying to stick to single line headers wrapped in dashed brackets, but like in point one, avoid the asterisks and TURN YOUR CAPS LOCK OFF. 

Data specs and definitions:

ILE RPG and all the flavors of RPG are considered a strongly typed language.  In comparison, PHP is a loosely typed language.  This does not indicate that with force you pound the code into the system but that each data element or constant in a program that it exists in its namespace and container as a unique item with a defined type that is clearly defined.  Having a variable $cost defined as a 12 P 2 type field (12 byte packed with 2 decimal places) strongly types the variable.  If this variable is specified in the data specs it will exist in the entire program as this strongly typed item.  Define your data specs clearly, place items into scopes that can be encapsulated in procedures or other modules, and avoid unneeded items by better planning.

Also before we move on, indent your data elements, and qualify your data structures.  Make this area of your application clean and organized, and everything in its proper place.

The main program:

Here is the walkthrough of the operations.  Like many ILE RPG programs, this is a procedural run, or start at the top and work your way to the bottom.  I was influenced heavily by Scott Klement early on in my development career and almost always move LR on in my first line of executed code.  This way the program ends as soon as all the executable RPG is done running.  It seems like a small thing, but try searching through a 20,000-line RPG monolith program for where the program should terminate and end.  This just says to the program, when you’re done, I am done so let’s end this thing right away. 

 Here is the narrative to the program:     

  • Move LR on
  • Let’s set some SQL options as global settings to help us out in a one-time statement
  • We are using SQL to retrieve all of the data that corresponds to the default criteria
  • Declare the SQL cursor (this gets the data)
  • Open the SQL cursor declaration (get the data)
  • If the SQL return code (more on this later) is OK (all is good), go row by row through the data retrieved in the SQL cursor
  • Fetch the data into inbound fields (defined in a qualified data structure)
  • Check to see if the data in the SQL row exists in the outbound table, if not update it, else continue on)
  • If the data does not exist in the outbound table, clear a fresh record format (setting all the fields to default values based on the file field definitions.  See how your data is built is important.)
  • Populate the fields with the correct data types and values.
  • Write the record to the file (populating the file)
  • If the SQL cursor contains more records, repeat, and loop, else end and finish.
  • The previously set on LR ends the program.

Beautiful Code:

Beautiful code exists in ILE RPG.  This program may not be complex, unique, or sexy, but it does have a few elements of beautiful characteristics that I would like to share.

Good white space exists between lines when needed, not too much, not too little. White space helps keep the thoughts together just like in the spacing between paragraphs in this article.  Become a white space expert and write beautiful code.

Simple but direct comments.  Comments come and go, but make sure they are editable and able to simply guide another programmer through the code.

  Utilize good naming conventions.  More on this later, in this scenario I am lifting data from our ERP system to a file built to be utilized in an extension of the same database, so the field names are similar, but with the named and declared fields and constants, they should be readable.

CaMel CaseIng Your TexT can be IrritatinG and HArd to REAd.  Develop a naming and casing style which others can read and that flows to the eyes.  And oh yes, TAKE OUR CAPS LOCK OFF and write in lower case.  Your code should speak, not scream.

  Indent your code like a pro.  The code may be complex, but it will only ever get more complex, so indent well and help the next guy who comes along and has to fit their idea in your code.

Conclusion:

This is just a start to the journey of writing beautiful code.  ILE RPG can be a beautiful modern language, but although the opportunities are there, it is all how you put it together and say it that counts.  In the world of literature, author Neal Gaiman uses the same language I use, but he has the ability and skill to put those words together into something that is wonderful, masterful, and beautiful.  You can code in the same language (ILE RPG) as others, but it is up to you to make it beautiful.  I am not done by all means in making the changes and tweaks to make coding an art form.  There is so much room for improvement and with this improvement, I get better and the systems I work on have real quality software delivered.  Beautiful code leads to better logic, better testing, more thought, and a better product.

Shift happens, make it beautiful.

I have learned it's hard to beat embedded sql paired with long descriptive named procedures (internally or externally when re-usable) to clearly speak for the code. And when the procedure can be a function to return a valuable biz rule it becomes truly bulletproof and reads like a novel. Hate to say it but I code less and less rpg these days. The rpg pgm is merely the shell that facilitates the harmony among sql and procedure calls.

I very much agree with the need for clear, clean, elegant code no matter what language it is written in. And there is really no excuse for ILE RPG. Especially now that we have formatting and variable rename support in tooling like RDi. I was thinking that using free form D-Specs would make the code even cleaner and finally break free from the punch card heritage. I understand that not every system can use it. But anyone from V7R1 can and it is a dramatic improvement to readability.

Bryan Meyers wrote the best style guide for RPG many years ago. In my humble opinion, I still feel it is the best out there. Most RPG developers have never read it. It is a great go-to for many shops and consultants. I also feel that it is time for the ILE-RPG language to collaborate and develop the next generation style and standards guide for the language and move forward to set it as our Magna Carta Rosetta Stone for the 21st century. There are always many great suggestions for how to write better code in our beloved language, but they tend to live in the comments in forums and within the walls of companies where the developers live and work. One of the efforts of the team at www.ile-rpg.org is to start centralizing our efforts together and build upon this common ground for our generation and the next. It is the only way this platform is going to survive. I want to write beautiful code and create relevant, powerful, software for the industries I serve. If you are reading this I believe that you too feel this way. I encourage you to help standardize and centralize the standards that will bring greater power to this language.

I great topic to pick. I really appreciate the effort and I agree with most of it but the code doesn't represent this. Why add a comment on the SQL set option statement? It is totally clear that you are set some sql options. No comment needed. Same goes for the declaring of the sql cursor. The code speaks for itself. Why the comment?! Or the table loop comment, totally superfluous. The comment on the chain below is much better because it does not comment what it technically does but what the intention was. And you speak of good names but what the h*** should cData.cono be. Off-topic: And why not use qualified data structures to access files with record level access? AFAIR that is supported with 7.1.

To view or add a comment, sign in

More articles by Michael Moegling MBA

  • The Transactional Echo Necessity

    The Echo Chamber and the Mountain Imagine standing inside an echo chamber and letting out a full-throated yell. The…

    5 Comments
  • Think Forward and Differently

    For the original article, you can view it here https://mikemoegling.com/2024/09/17/think-forward-and-differently/…

  • Surprise the Judges – Add the Secret Sauce

    In our scant free time my wife and I have taken to watching different series on Netflix. In the beginning we struggled…

    1 Comment
  • Top Five Things I Learned Writing RPG

    As of today, I am looking at nearly a year and half since the last time I worked on an IBM i system (AS/400, iSeries…

    3 Comments
  • Shift Happens: 1 - Foundations, Toolboxes, and Cutting Code

    (Note: This was originally written for ILE-RPG Language RPG Unleashed. Passionate about RPG? Join us on the journey) If…

    3 Comments
  • Are You Moving at the Speed of Business?

    At the root of what we do and who we are as professionals in business who operate out of an IT toolbox, is the need to…

  • The Buying and Selling of RPG

    They Buying and Selling of RPG I remember it well, and for a good reason, it was how another programmer, one who I…

    9 Comments
  • I’m not a RPG Programmer

    Originally published @ Medium I'm Not A RPG Programmer I’m not a RPG programmer. RPG as in the proprietary programming…

    13 Comments
  • Web Developer/Graphic Designer

    Koroseal Interior Products is searching for a Web Developer/Graphic Designer. Below is the job specifics.

Others also viewed

Explore content categories