Sie sind auf Seite 1von 42

• Click to add text

ILE RPG IV Best Practices

Jim Diephuis (diephuis@us.ibm.com)

© 2011 IBM Corporation


Where credit is due:
RPG IV Style, Standards, and Best Practices
By Bryan Meyers
http://www.bmeyers.net/resources/rpgivstyle.php

Barbara Morris
IBM Toronto Lab
RPG Compiler Development

2 05/01/12
2 IBM STG Lab Services and Training © 2011 IBM Corporation
Use Free Format

3 05/01/12
3 IBM STG Lab Services and Training © 2011 IBM Corporation
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

/Free
TotalPay = (RegHours * Rate) +
(OvtHours * Rate * 1.5) +
(DblHours * Rate * 2);
/End-free

4 05/01/12
4 IBM STG Lab Services and Training © 2011 IBM Corporation
Use Free Format
Structured 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

5 05/01/12
5 IBM STG Lab Services and Training © 2011 IBM Corporation
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

6 05/01/12
6 IBM STG Lab Services and Training © 2011 IBM Corporation
Embrace ILE

7 05/01/12
7 IBM STG Lab Services and Training © 2011 IBM Corporation
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

8 05/01/12
8 IBM STG Lab Services and Training © 2011 IBM Corporation
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

9 05/01/12
9 IBM STG Lab Services and Training © 2011 IBM Corporation
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)

10 05/01/12
10 IBM STG Lab Services and Training © 2011 IBM Corporation
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 signature


STRPGMEXP PGMLVL(*CURRENT)
EXPORT SYMBOL(openSocket)
EXPORT SYMBOL(sendBuffer)
EXPORT SYMBOL(receiveBufGE)
EXPORT SYMBOL(closeSocket)
ENDPGMEXP

11 05/01/12
11 IBM STG Lab Services and Training © 2011 IBM Corporation
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
12 05/01/12
12 IBM STG Lab Services and Training © 2011 IBM Corporation
Embrace ILE
D*--------------------------------------------------
D* Procedure name: century
D* Purpose: Take a 6 digit date and add the
D* centry to it.
D* Parameter: indate => 6 digit date
D* Returns: eight digit date
D*--------------------------------------------------
* Takes a 6 digit date and adds the century to it.
D century pr 8 0
D indate 6 0 const

D*--------------------------------------------------
D* Procedure name: getTime
D* Purpose: Get the current time and return it as 6 numeric
D* Returns: numeric 6 time value.
D*--------------------------------------------------
D getTime PR 6S 0

D*--------------------------------------------------
D* Procedure name: getDate
D* Purpose: Get the current date as numeric 6
D* Returns: numeric 6 date value
D*--------------------------------------------------
D getDate PR 6S 0

* prototypes
/copy tcpcodep TCP/IP prototypes
/copy dateutilp Date utility prototypes

13 05/01/12
13 IBM STG Lab Services and Training © 2011 IBM Corporation
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

14 05/01/12
14 IBM STG Lab Services and Training © 2011 IBM Corporation
Centralize Declarations

15 05/01/12
15 IBM STG Lab Services and Training © 2011 IBM Corporation
Centralize Declarations

 Organize all variables (and constants)


 Use predictable order
Prototype definitions (/COPY)
Internal prototype definitions
Named Constants
Data Structures
Standalone variables

• And alphabetize!

16 05/01/12
16 IBM STG Lab Services and Training © 2011 IBM Corporation
Centralize Declarations
 Declare literals as constants
* Constants for base message option value
d APPROVAL c 'A'
d CREDIT c 'C'

 Indent data item names


D ErrMsgDS DS
D ErrPrefix 3
D ErrMsgID 4
D ErrMajor 2 OVERLAY(ErrMsgID:1)
D ErrMinor 2 OVERLAY(ErrMsgID:3)

 Leave column 7 blank (on H-specs too!)


 Use length notation instead of positional
Avoid multiple occurrence data structures
 Use array data structures instead
17 05/01/12
17 IBM STG Lab Services and Training © 2011 IBM Corporation
Centralize Declarations
 Avoid compile-time arrays
D DaysCTData DS
D 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)

18 05/01/12
18 IBM STG Lab Services and Training © 2011 IBM Corporation
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)
/free
Customer.YTDSls = 0;
/end-free

19 05/01/12
19 IBM STG Lab Services and Training © 2011 IBM Corporation
Expand Naming
Conventions

20 05/01/12
20 IBM STG Lab Services and Training © 2011 IBM Corporation
Expand Naming Conventions
 Standardize
 Go beyond six! (but don’t get carried away)
 Describe the item
 Avoid special characters
 Use mixed case
D messagePtr s *
D messageLength s 10I 0
d messageBuffer s 1000 based(messagePtr)

 Maintain dictionary of names (Have a


naming convention)
21 05/01/12
21 IBM STG Lab Services and Training © 2011 IBM Corporation
Write Indicatorless Code

22 05/01/12
22 IBM STG Lab Services and Training © 2011 IBM Corporation
Write Indicatorless Code
 Eliminate numbered indicators
 Indicator data structure (INDDS)
fWrkCustD cf e k workstn indds(indicators)

d indicators ds
d Exit n overlay(indicators:3)
d Cancel n overlay(indicators:12)

/free
if Exit or Cancel;
*inlr=*on;
endif;
/end-free

23 05/01/12
23 IBM STG Lab Services and Training © 2011 IBM Corporation
Write Indicatorless Code

Assign meaningful names


d indicators ds
d 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

24 05/01/12
24 IBM STG Lab Services and Training © 2011 IBM Corporation
Write Indicatorless Code

Include description of ones you do use


 Level break indicators or U1-U8
 Use the Boolean data type

25 05/01/12
25 IBM STG Lab Services and Training © 2011 IBM Corporation
Use Structured
Programming Techniques

26 05/01/12
26 IBM STG Lab Services and Training © 2011 IBM Corporation
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

27 05/01/12
27 IBM STG Lab Services and Training © 2011 IBM Corporation
Manipulate Character
Strings

28 05/01/12
28 IBM STG Lab Services and Training © 2011 IBM Corporation
Manipulate Character Strings

 Avoid arrays and data structures for string


manipulation
 Use string manipulation op codes and
BIFs
/FREE
Full = %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

29 05/01/12
29 IBM STG Lab Services and Training © 2011 IBM Corporation
Manipulate Character Strings

Use free form EVAL (a = b) for string


manipulation
 Use %subst or %replace to not pad with
blanks

30 05/01/12
30 IBM STG Lab Services and Training © 2011 IBM Corporation
Manipulate Character Strings
 Use variable-length fields to simplify string
handling
D QualName S 33 VARYING
D Library S 10 VARYING
D File S 10 VARYING
D Member S 10 VARYING

/FREE
QualName = Library + '/' + File + '(' + Member + ')';
/END-FREE
instead of this:

D QualName S 33
D Library S 10
D File S 10
D Member S 10

/FREE
QualName = %TRIM(Library) + '/' + %TRIM(File)
+ '(' + %TRIM(Member) + ')';
/END-FREE
31 05/01/12
31 IBM STG Lab Services and Training © 2011 IBM Corporation
Use Comments Judiciously

32 05/01/12
32 IBM STG Lab Services and Training © 2011 IBM Corporation
Use Comments Judiciously

 Use // comments exclusively


// Prototypes
D DayofWeek PR 1 0
D VarDate D

// Standalone variables
D DayNbr S 5 0

/Free
// Calculate total pay for employee
Chain(ne) EmployeeID Employees;
If %Found; // If employee active, calculate total pay
Eval(h) TotalPay = (RegHours * Rate) + (OvtHours * Rate * 1.5);
Endif;
/End-free

33 05/01/12
33 IBM STG Lab Services and Training © 2011 IBM Corporation
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
//
//*****************************************************************
34 05/01/12
34 IBM STG Lab Services and Training © 2011 IBM Corporation
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
//
//*****************************************************************

35 05/01/12
35 IBM STG Lab Services and Training © 2011 IBM Corporation
Use Comments Judiciously

 Use blank lines to group related source


 Avoid right-hand comments (column 81 – 100)
 Stop using sequence numbers on left

36 05/01/12
36 IBM STG Lab Services and Training © 2011 IBM Corporation
Avoid Obsolescence

37 05/01/12
37 IBM STG Lab Services and Training © 2011 IBM Corporation
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

38 05/01/12
38 IBM STG Lab Services and Training © 2011 IBM Corporation
Parting Shots

39 05/01/12
39 IBM STG Lab Services and Training © 2011 IBM Corporation
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

40 05/01/12
40 IBM STG Lab Services and Training © 2011 IBM Corporation
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

41 05/01/12
41 IBM STG Lab Services and Training © 2011 IBM Corporation
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:

AS/400 e-business on demand OS/400

AS/400e IBM i5/OS

eServer IBM (logo)

iSeries

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.

42 05/01/12
42 IBM STG Lab Services and Training © 2011 IBM Corporation

Das könnte Ihnen auch gefallen