Forum

Shift Happens: 2 – ...
 
Notifications
Clear all

Shift Happens: 2 – Write Beautiful Code by Mike Moegling

1 Posts
1 Users
0 Reactions
416 Views
Adsero Optima
Posts: 35
Member Admin
Topic starter
 

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 anymore?

 

RPG, or as it should be called now ILE RPG, is a sophisticated and transformed software development language that is geared to run over huge data sets and transaction processing tasks to deliver cutting edge information transfer with extreme accuracy and 99.999999% online up-time. With some Googling it is completely possible to follow the language through its various shifts in the development sphere.  It 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 .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 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 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.  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.  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.

 

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.

 

      * ----------------------------------------------------------------------
      * Program:     CDSK01P
      * Programmer:  Mike Moegling
      * Date:        Dec 5, 2016
      * Purpose:     CDSK - Load and Refresh Credit Controllers
      * ----------------------------------------------------------------------
      * Revision History
      * ----------------------------------------------------------------------
      * Mod       Date        Programmer           Description
      *----       --------    ---------------      ---------------------------
      *
      *
      *
      * -----------------------------------------------------------------------
     H option(*noDebugIO)
     H dftactgrp (*no)
     H actgrp ('KIP')
   
      * -----------------------------------------------------------------------
      * Files
      * -----------------------------------------------------------------------
      * CDSK - Credit Desk Application Individual Users
     fcdsk02f   uf a e           k disk
   
      * -------------------------------------------------------------------------
      * data descriptions and definitions
      * -------------------------------------------------------------------------
     D true            C                   const('1')
     D false           C                   const('0')
     D yes             C                   const('Y')
     D no              C                   const('N')
     D Ok              C                   0
   
     D date            S               D   inz(*sys)
     D time            S               T   inz(*sys)
     D user            S             10A   inz(*user)
     D notFound        S             10A   inz('Not Found')
   
     D $index          S              9p 0 inz(0)
   
     D cData           ds                  qualified
     d  cono                          2a
     d  crsp                          4a
   
      *  --------------------------------/Program/---------------------------------
      /free
   
       // program startup
         *inlr = true;
   
         // Set SQL options
         exec sql set option datfmt=*iso, commit=*none;
   
         // Declare/open SQL cursor
         exec sql declare creditDesk cursor for
         select cono00 , pmcd60 from kipco
            left join  cdsk_ctl on cono00 = cono60
         for fetch only;
   
         Exec Sql Open creditDesk;
   
         // Table read loop
         dow sqlcode = ok;
         exec sql fetch creditDesk Into :cData;
           if sqlcode = ok;
   
               // check to see if the credit controller exists, if not add to file
               chain (cData.cono : cData.crsp) cdsk02f;
               if not %found(cdsk02f);
                  clear cdr02;
   
                     $index = $index + 1;
   
                     indx02 = $index;          // File Index
                     cono02 = cData.cono;      // Company Code
                     crsp02 = cData.crsp;      // Credit Controller
                     usid02 = notFound;        // Credit User ID
                     extc02 = false;           // Extension Code
                     sabv02 = *blanks;         // State or Providence
                     data02 = date;            // Date Added
                     tima02 = time;            // Time Added
                     usea02 = user;            // User Added
                     datc02 = date;            // Date Changed
                     timc02 = time;            // Time Changed
                     usec02 = user;            // User Changed
   
                  write cdr02;
               endif;
   
           endif;
         enddo;
   
      /end-free
   

 

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 up line 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 YOUR CAPS LOCK OFF and write in lower case.  Your code should speak, not scream.
  • Indent your code like a pro.  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 Gaimen 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.

 
Posted : 26/01/2021 12:14 pm