• Click to add text
© 2011 IBM Corporation
ILE RPG IV Best Practices
Jim Diephuis ([email protected])
© 2011 IBM Corporation22 IBM STG Lab Services and Training05/01/12
Where credit is due: RPG IV Style, Standards, and Best Practices By Bryan Meyershttp://www.bmeyers.net/resources/rpgivstyle.php
Barbara MorrisIBM Toronto LabRPG Compiler Development
© 2011 IBM Corporation33 IBM STG Lab Services and Training05/01/12
Use Free Format
© 2011 IBM Corporation44 IBM STG Lab Services and Training05/01/12
Use Free Format Easier to read
Easier to document
Easier to maintain
Many new features supported only in free-format
But don’t abandon using column alignment
/FreeTotalPay = (RegHours * Rate) +
(OvtHours * Rate * 1.5) +(DblHours * Rate * 2);
/End-free
© 2011 IBM Corporation55 IBM STG Lab Services and Training05/01/12
Use Free FormatStructured Format Free Format
/FREE
KEY SETLL DBFILE setll key dbfile;IF %EQUAL if %equal;
KEY READE DBFILE reade key dbfile;DOW NOT %EOF(DBFILE) dow not %eof(dbfile);
KEY2 CHAIN FILE2 chain key2 file2;IF %FOUND(FILE2) if %found(file2); EVAL P1DESC=DBDESC p1desc=dbdesc;ELSE else;EVAL P1DESC=*BLANK p1desc=*blank;ENDIF endif;WRITE Detail write detail;
KEY READE DBFILE reade key dbfile;ENDDO enddo;ELSE else;WRITE ErrorMsg write ErrorMsg;ENDIF endif;
/END-FREE
© 2011 IBM Corporation66 IBM STG Lab Services and Training05/01/12
Use Free Format If writing new code, use free format
If changing existing code, use free format to
Replace entire subroutines
Replace large sections of code
© 2011 IBM Corporation77 IBM STG Lab Services and Training05/01/12
Embrace ILE
© 2011 IBM Corporation88 IBM STG Lab Services and Training05/01/12
Embrace ILE USE PROCEDURES
Modular approach to programming
• Way to organize an application
• Facilitates program maintenance
• Hides complex logic
• Efficient reuse of code – NO DUPLICATE CODE
• Smaller, more efficient, single function units
© 2011 IBM Corporation99 IBM STG Lab Services and Training05/01/12
Embrace ILE Use Binding Directories
Organize the pieces required to create a program
• Refer to directory instead of explicitly listing components
Use consistent strategy
• Generic binding directory for reusable code across applications
• Application specific binding directory
© 2011 IBM Corporation1010 IBM STG Lab Services and Training05/01/12
Embrace ILE Use Service Programs
Procedure will be in more than one or two programs? Package it into a service program.
Use ACTGRP(*CALLER) CRTSRVPGM SRVPGM(PCIIBMLIB/MASKPRC) EXPORT(*SRCFILE) + SRCFILE(QSRVSRC) SRCMBR(*SRVPGM) ACTGRP(*CALLER)
© 2011 IBM Corporation1111 IBM STG Lab Services and Training05/01/12
Embrace ILE Use binder language
Don’t use EXPORT(*ALL)
CRTsrvpgm SRVPGM(ctyfrnlib/TCPCODE) MODULE(*SRVPGM) +
SRCFILE(CTYFRNLIB/QSRVSRC) TEXT('TCP/IP + procedures') BNDDIR(QZRDSAPI/QZRDSAPI)
Controls service program signatureSTRPGMEXP PGMLVL(*CURRENT) EXPORT SYMBOL(openSocket) EXPORT SYMBOL(sendBuffer) EXPORT SYMBOL(receiveBufGE) EXPORT SYMBOL(closeSocket) ENDPGMEXP
© 2011 IBM Corporation1212 IBM STG Lab Services and Training05/01/12
Embrace ILE Use Prototypes
Defines parameters and interfaces
Avoids run time errors
Allows coding literals and expressions
Declare parameter lists in D-specs
Pass by value and read only reference
Store prototypes in /COPY members
Save typing the prototype each time
© 2011 IBM Corporation1313 IBM STG Lab Services and Training05/01/12
Embrace ILED*--------------------------------------------------D* Procedure name: centuryD* Purpose: Take a 6 digit date and add theD* centry to it.D* Parameter: indate => 6 digit dateD* Returns: eight digit dateD*--------------------------------------------------* Takes a 6 digit date and adds the century to it.
D century pr 8 0D indate 6 0 const
D*--------------------------------------------------D* Procedure name: getTimeD* Purpose: Get the current time and return it as 6 numericD* Returns: numeric 6 time value.D*--------------------------------------------------D getTime PR 6S 0
D*--------------------------------------------------D* Procedure name: getDateD* Purpose: Get the current date as numeric 6D* Returns: numeric 6 date valueD*--------------------------------------------------D getDate PR 6S 0
* prototypes/copy tcpcodep TCP/IP prototypes/copy dateutilp Date utility prototypes
© 2011 IBM Corporation1414 IBM STG Lab Services and Training05/01/12
Embrace ILE Include constant declarations in prototype
“globalize” the constant
Use IMPORT/EXPORT only for global data
“Hidden interface”
Limit to values set once and not changed
Use CONST instead of VALUE for large parameters and data structures
© 2011 IBM Corporation1515 IBM STG Lab Services and Training05/01/12
Centralize Declarations
© 2011 IBM Corporation1616 IBM STG Lab Services and Training05/01/12
Centralize Declarations
Organize all variables (and constants)
Use predictable orderPrototype definitions (/COPY)
Internal prototype definitions
Named Constants
Data Structures
Standalone variables
• And alphabetize!
© 2011 IBM Corporation1717 IBM STG Lab Services and Training05/01/12
Centralize Declarations
Declare literals as constants * Constants for base message option value
d APPROVAL c 'A'
d CREDIT c 'C'
Indent data item namesD ErrMsgDS DS
D ErrPrefix 3D ErrMsgID 4D ErrMajor 2 OVERLAY(ErrMsgID:1)D ErrMinor 2 OVERLAY(ErrMsgID:3)
Leave column 7 blank (on H-specs too!) Use length notation instead of positionalAvoid multiple occurrence data structures Use array data structures instead
© 2011 IBM Corporation1818 IBM STG Lab Services and Training05/01/12
Centralize Declarations Avoid compile-time arrays
D DaysCTData DSD 9 Inz('Sunday')D 9 Inz('Monday')D 9 Inz('Tuesday')D 9 Inz('Wednesday')D 9 Inz('Thursday')D 9 Inz('Friday')D 9 Inz('Saturday')D Days 9 Dim(7)D Overlay(DaysCTData)
© 2011 IBM Corporation1919 IBM STG Lab Services and Training05/01/12
Centralize Declarations Use qualified data structures
Good documentation Allows same name in different data structures
d Customer ds Qualified d Name 20a overlay(customer)d YTDSls 11s 2 overlay(customer:*next)/freeCustomer.YTDSls = 0;
/end-free
© 2011 IBM Corporation2020 IBM STG Lab Services and Training05/01/12
Expand Naming Conventions
© 2011 IBM Corporation2121 IBM STG Lab Services and Training05/01/12
Expand Naming Conventions
Standardize
Go beyond six! (but don’t get carried away)
Describe the item
Avoid special characters
Use mixed caseD messagePtr s *D messageLength s 10I 0d messageBuffer s 1000 based(messagePtr)
Maintain dictionary of names (Have a naming convention)
© 2011 IBM Corporation2222 IBM STG Lab Services and Training05/01/12
Write Indicatorless Code
© 2011 IBM Corporation2323 IBM STG Lab Services and Training05/01/12
Write Indicatorless Code
Eliminate numbered indicators
Indicator data structure (INDDS)fWrkCustD cf e k workstn indds(indicators)
d indicators dsd Exit n overlay(indicators:3) d Cancel n overlay(indicators:12)
/freeif Exit or Cancel;*inlr=*on;
endif;/end-free
© 2011 IBM Corporation2424 IBM STG Lab Services and Training05/01/12
Write Indicatorless Code
Assign meaningful namesd indicators dsd Exit n overlay(indicators:3) d Cancel n overlay(indicators:12)d PatNbrErr n overlay(indicators:50)d PatNamErr n overlay(indicators:51)d PatAdrErr n overlay(indicators:52)
Use Built-in Functions (BIFs)
Use file exception conditions
• %eof, %found, %error
© 2011 IBM Corporation2525 IBM STG Lab Services and Training05/01/12
Write Indicatorless Code
Include description of ones you do use
Level break indicators or U1-U8
Use the Boolean data type
© 2011 IBM Corporation2626 IBM STG Lab Services and Training05/01/12
Use Structured Programming Techniques
© 2011 IBM Corporation2727 IBM STG Lab Services and Training05/01/12
Use Structured Programming Techniques
DO use: IF, DOU, DOW, WHEN, FOR
end them with ENDIF, ENDDO, ENDSL
Multi-path compares use SELECT
DON’T use: GOTO, CABxx, COMP, CASxx
DO use ITER, LEAVE, LEAVESR
© 2011 IBM Corporation2828 IBM STG Lab Services and Training05/01/12
Manipulate Character Strings
© 2011 IBM Corporation2929 IBM STG Lab Services and Training05/01/12
Manipulate Character Strings
Avoid arrays and data structures for string manipulation
Use string manipulation op codes and BIFs
/FREEFull = %TRIMR(FirstName) + ‘ ‘ +
%SUBST(MidName:1:1) + ‘ ‘ +LastName;
Result = ‘It is ‘ + %CHAR(Time) +‘ on ‘ + %CHAR(Date);
Sal = ‘The annual salary is ‘+ %TRIM(%EDITC(Amt*12 : ’A’ : *CURSYM));
/END-FREE
© 2011 IBM Corporation3030 IBM STG Lab Services and Training05/01/12
Manipulate Character Strings
Use free form EVAL (a = b) for string manipulation
Use %subst or %replace to not pad with blanks
© 2011 IBM Corporation3131 IBM STG Lab Services and Training05/01/12
Manipulate Character Strings
Use variable-length fields to simplify string handling
D QualName S 33 VARYINGD Library S 10 VARYINGD File S 10 VARYINGD Member S 10 VARYING
/FREEQualName = Library + '/' + File + '(' + Member + ')';
/END-FREEinstead of this:
D QualName S 33D Library S 10D File S 10D Member S 10
/FREEQualName = %TRIM(Library) + '/' + %TRIM(File)
+ '(' + %TRIM(Member) + ')';/END-FREE
© 2011 IBM Corporation3232 IBM STG Lab Services and Training05/01/12
Use Comments Judiciously
© 2011 IBM Corporation3333 IBM STG Lab Services and Training05/01/12
Use Comments Judiciously
Use // comments exclusively
// Prototypes
D DayofWeek PR 1 0D VarDate D
// Standalone variablesD DayNbr S 5 0
/Free// Calculate total pay for employeeChain(ne) EmployeeID Employees;If %Found; // If employee active, calculate total payEval(h) TotalPay = (RegHours * Rate) + (OvtHours * Rate * 1.5);
Endif;/End-free
© 2011 IBM Corporation3434 IBM STG Lab Services and Training05/01/12
Use Comments Judiciously Use prolog on all programs
//******************************************************************
//// Service Program: XXXXXML//// Description:// This service program contains the procedures used to parse XML// data that is received from where ever and convert it into a// string that matches a given data structure.//// External Procedures:// XMLInit - Initialize the user index and parser.// XMLParse - Parse the XML into a given data structure.// XMLParseEnd - End parsing.//// Internal Procedures:// ProcessChars - Process characters returned from the parser// ProcessField - Process a given field// ProcessStart - Process a new tag// ProcessEnd - Process the end of a tag//// Change Information:// date Profile Reason// ---------- ---------- ----------------------------------------// 2003-03-13 IBMJIMH Initial writing////*****************************************************************
© 2011 IBM Corporation3535 IBM STG Lab Services and Training05/01/12
Use Comments Judiciously
Use prolog on all procedures //*****************************************************************// Procedure: XMLInit//// Description:// Initialize the index using the entries in DSPARSE. The index is// used to define the parts of the data structures that may be// parsed.// Also initialize the parser with the procedures that will be used// on it's callbacks.// All of these things only need to be done once within a job.//// Parameters:// none//// Return value:// none////*****************************************************************
© 2011 IBM Corporation3636 IBM STG Lab Services and Training05/01/12
Use Comments Judiciously
Use blank lines to group related source
Avoid right-hand comments (column 81 – 100)
Stop using sequence numbers on left
© 2011 IBM Corporation3737 IBM STG Lab Services and Training05/01/12
Avoid Obsolescence
© 2011 IBM Corporation3838 IBM STG Lab Services and Training05/01/12
Avoid Obsolescence Eliminate obsolete operation codes
If free-form doesn’t support it…
If there is a function and opcode that do same thing, use the function
Avoid program described files
Use native date data types for date operations
Work on character fields as well
© 2011 IBM Corporation3939 IBM STG Lab Services and Training05/01/12
Parting Shots
© 2011 IBM Corporation4040 IBM STG Lab Services and Training05/01/12
Parting Shots Avoid programming tricks
Or make sure they are well documented
Don’t worry about relative performance
Use whatever best fits the task at hand
© 2011 IBM Corporation4141 IBM STG Lab Services and Training05/01/12
Parting Shots
Make it right before you make it faster
Keep it right when you make it faster
Make it clear before you make it faster
Don’t sacrifice clarity for small gains in efficiency
© 2011 IBM Corporation4242 IBM STG Lab Services and Training05/01/12
Trademarks and Disclaimers© IBM Corporation 1994-2005. All rights reserved.References in this document to IBM products or services do not imply that IBM intends to make them available in every country.
The following terms are trademarks of International Business Machines Corporation in the United States, other countries, or both:
Rational is a trademark of International Business Machines Corporation and Rational Software Corporation in the United States, other countries, or both.Java and all Java-based trademarks are trademarks of Sun Microsystems, Inc. in the United States, other countries, or both.Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the United States, other countries, or both. Intel, Intel Inside (logos), MMX and Pentium are trademarks of Intel Corporation in the United States, other countries, or both.UNIX is a registered trademark of The Open Group in the United States and other countries.SET and the SET Logo are trademarks owned by SET Secure Electronic Transaction LLC. Other company, product or service names may be trademarks or service marks of others.
Information is provided "AS IS" without warranty of any kind.
All customer examples described are presented as illustrations of how those customers have used IBM products and the results they may have achieved. Actual environmental costs and performance characteristics may vary by customer.
Information concerning non-IBM products was obtained from a supplier of these products, published announcement material, or other publicly available sources and does not constitute an endorsement of such products by IBM. Sources for non-IBM list prices and performance numbers are taken from publicly available information, including vendor announcements and vendor worldwide homepages. IBM has not tested these products and cannot confirm the accuracy of performance, capability, or any other claims related to non-IBM products. Questions on the capability of non-IBM products should be addressed to the supplier of those products.
All statements regarding IBM future direction and intent are subject to change or withdrawal without notice, and represent goals and objectives only. Contact your local IBM office or IBM authorized reseller for the full text of the specific Statement of Direction.
Some information addresses anticipated future capabilities. Such information is not intended as a definitive statement of a commitment to specific levels of performance, function or delivery schedules with respect to any future products. Such commitments are only made in IBM product announcements. The information is presented here to communicate IBM's current investment and development activities as a good faith effort to help with our customers' future planning.
Performance is based on measurements and projections using standard IBM benchmarks in a controlled environment. The actual throughput or performance that any user will experience will vary depending upon considerations such as the amount of multiprogramming in the user's job stream, the I/O configuration, the storage configuration, and the workload processed. Therefore,
no assurance can be given that an individual user will achieve throughput or performance improvements equivalent to the ratios stated here.
Photographs shown are of engineering prototypes. Changes may be incorporated in production models.
AS/400 e-business on demand OS/400
AS/400e IBM i5/OS
eServer IBM (logo)
iSeries