ABAP/4 Programming Standards: SAP Technical / Manufacturing / IS Auto Sreekanth Dhadi
ABAP/4 Programming Standards: SAP Technical / Manufacturing / IS Auto Sreekanth Dhadi
CONTENTS
ABAP/4 PROGRAMMING STANDARDS.......................................................................................................1 1NAMING CONVENTIONS ....................................................................................................................................1 1.1Program Naming..................................................................................................................................1 1.2Data Dictionary Entries.......................................................................................................................2 1.3Logical Database.................................................................................................................................3 1.4Pool table naming standard.................................................................................................................3 1.5Views....................................................................................................................................................4 1.6Data Elements......................................................................................................................................7 1.7Domain................................................................................................................................................7 1.8Message Class......................................................................................................................................8 1.9Module Pools.......................................................................................................................................8 1.10Functions...........................................................................................................................................9 1.11Transaction Codes...........................................................................................................................10 1.12Variants............................................................................................................................................10 1.13Parameter IDs..................................................................................................................................11 1.14Jobs..................................................................................................................................................11 1.15Batch Data Communication Sessions...............................................................................................12 1.16Unit Test Cases................................................................................................................................12 1.17Variable Names................................................................................................................................13 1.18Layout Set Names.............................................................................................................................13 2ABAP STANDARD CONVENTIONS...................................................................................................................14 2.1Program Attributes.............................................................................................................................14 2.2Development Class.............................................................................................................................15 2.3Change Request Number....................................................................................................................15 2.4Program Internal Structures..............................................................................................................15 2.5Program Variable tbl_errors Names..................................................................................................17 2.6Messages............................................................................................................................................20 2.7PF Status............................................................................................................................................21 2.8Variants..............................................................................................................................................22 2.9Batch Input Sessions..........................................................................................................................22 2.10Modules and Forms..........................................................................................................................23 2.11Batch Job Names..............................................................................................................................23 2.12Job Names / Copy Requests..............................................................................................................24 3ABAP PROGRAMMING STANDARDS AND PRACTICES.........................................................................................24 3.1Program Structure.............................................................................................................................24 3.2Main Documentation Block................................................................................................................25 3.3Modularity.........................................................................................................................................25 3.4Statement Formatting.........................................................................................................................25 3.5Parameters and Select Options..........................................................................................................25 3.6Validation of Input Fields..................................................................................................................26 3.7Messages............................................................................................................................................26 3.8Data Access........................................................................................................................................26 3.9Data Update.......................................................................................................................................27 3.10External File Usage.........................................................................................................................27 3.11Authorization Checking....................................................................................................................27 3.12Lock Objects.....................................................................................................................................28 3.13Debugging........................................................................................................................................28 3.14Standards for Specific Statements....................................................................................................28 3.15Maintenance/Correction of Existing Code.......................................................................................41 3.16ABAP/4 Programming Practices......................................................................................................42
Internal Use
ii
APPENDIX
APPENDIX A: TABLE OF APPLICATION AREA CODES......................................................................45 APPENDIX B.......................................................................................................................................................46 ZZSAMPLE: SAMPLE PROGRAM STRUCTURE.....................................................................................46 APPENDIX C: DEVELOPMENT CLASSES.................................................................................................49 APPENDIX D......................................................................................................................................................49 REQUIREMENT AND DESIGN REVIEWS.................................................................................................49 CODE REVIEWS...............................................................................................................................................50
Internal Use
iii
1
1.1
Naming Conventions
Program Naming XXXX Global/Local development Z Y Global Local SAP Module Area A B C F H I L M P Q R S Asset Management Basis Controlling Finance Human Resource Industry Solutions Plant Maintenance Materials Management Production Planning Quality Management Project System Sales and Distribution
Z M T O where Z
Internal Use
Program Type I R S U X C Interface Report SAPscript ABAP Utility User Exit Conversions Object Type P I M F S J K Program Include Module Pool Function Group Subroutine Pool Interface Definition Class Definition Any combination of characters (choose a meaningful
1.2
XXXX name)
Tables
The naming convention for transparent tables, clusters and pools is as follows: ZMNNNNNNNN where Z Global/Local development Z Y Global Local SAP Module Area A B C F Asset Management Basis Controlling Finance
Internal Use 2
1.3
H I L M P Q R S
Human Resource Industry Solutions Plant Maintenance Materials Management Production Planning Quality Management Project System Sales and Distribution
N Alpha-numeric name for Internal table, cluster or pool; can be from 3 through 8 characters in length. Logical Database
The naming convention for logical database is as follows: ZNN where Z Global/Local development Z Y Global Local Alpha-numeric name for logical database
1.4
NN
ZNNNN where Z Global/Local development Z Y Global Local Logical pool table name
NNNN
Note: Table name in SAP are unique by the first 7 characters only.
Internal Use
Global/Local development Z Y Global Local SAP Module Area A B C F H I L M P Q R S Asset Management Basis Controlling Finance Human Resource Industry Solutions Plant Maintenance Materials Management Production Planning Quality Management Project System Sales and Distribution Dummy table name Fixed value
TTTT LK1
Views
A view provides an alternative way to retrieve data from a table or groups of tables. You can reduce the number of views by defining a view that contains related data from several tables. A view is a logical table and is not physically stored. SAP views differ from standard views because only the tables already linked by appropriate foreign keys in the Data Dictionary can be joined. ZV_M NNNNNN ZV Global/Local development ZV YVLocal SAP Module Area A Asset Management
Internal Use 4
Global
B C F H I L M P Q R S
Basis Controlling Finance Human Resource Industry Solutions Plant Maintenance Materials Management Production Planning Quality Management Project System Sales and Distribution View name
NNNNNN
Exception 1: Help Views are needed when F4 possible entries require more than just the key values stored in a table. Usually both the key values (for example, codes) and the associated text are required. The View will contain both the key and text fields. Only one Help View can be built per table. The naming standard for Help View is as follows: ZV ttttt HF1 Where ZV Global/Local development ZV YVLocal Help for table name Fixed value Global
TTTTT HF1
Internal Use
A matchcode is a logical table which is physically stored as an array. It consists of data components from one or more SAP logical tables. A matchcode is a cross between a logical view and a secondary index. It provides a way of accessing primary tables using non-key attributes (for example, fields) of various tables. Since the data is physically stored, matchcodes represent a data redundancy, which must be kept in synch with the primary tables it is linked with.
Matchcode Objects
NNN
Matchcode IDs
The matchcode ID objects use the matchcode object View to build physical tables. Physically, SAP builds a pool where the matchcode object name is prefixed with M_ as the pool name. Each matchcode object ID is setup as a logical pool table where the ID (1-Zpossible 36 IDs) is the suffix of the pool name. The following is an example of matchcode object, matchcode pool and matchcode (pool) IDs: Matchcode object name Mathcode pool name CUST M_CUST
Matchcode (pool) ID name M_CUSTA Matchcode (pool) ID name M_CUSTB The matchcode ID is where the redundancy update type is defined. SAP generates a function module which updates the data of the primary tables used by the matchcode object. The function module name is MC_UPDATE_matchcode object-name. XXXX1 where XXXX I Existing matchcode name Existing matchcode identifier (0-9, A-Z)
Internal Use
1.6
Data Elements
The naming conventions for Data Element are as follows: ZMNNNNNNNN where Z Global/Local development Z Y A B C F H I L M P Q R S Global Local SAP Module Area Asset Management Basis Controlling Finance Human Resource Industry Solutions Plant Maintenance Materials Management Production Planning Quality Management Project System Sales and Distribution Alphanumeric name for data elements. Length can be from 3 through 8 characters
N
1.7
Domain
Domain naming conventions are as follows: ZXXXLLL _ NN where Z Global/Local development Z Y Global Local Data Element type
Internal Use 7
XXX
LLL _ N
CHR = Char INT = Integer DEC = Decimal DAT = Date Length (for example, 1, 10, 125) Underscore to separate length from counter Numeric counter
Message Class
The naming conventions for Message class are as follows: ZI where Z Global/Local development Z Y Global Local Messages passed from Custom Interfaces
I ZR where Z
R
1.9
Module Pools
The naming conventions for Module Pool are as follows: SAPMZNNN where SAPMZ Global/Local development Global Local
SAPMZ SAPMY
Internal Use
NNN
A module pool consists entirely of INCLUDE programs. Use the following examples as a standard.
Data module
INCLUDE MZnnnTOP
Header with data declarations including tables (alphabetically sorted) and DATA statements
PBO modules
Subroutine modules
INCLUDE MZnnnF10
Subroutines where ZNNN corresponds to the last four characters of the module pool name
1.10
Functions
Frequently used routines can be created as function modules. These are accessed by ABAP/4 programs through the CALL FUNCTION statement and may be started across programs. The maximum length for function module names is 30 characters. Function modules are grouped within a function group. Function Groups Z XXX where Z Global/Local development Z Y Global Local
Internal Use
XXXX
Uniquely identifies the function module. Spell out the name when possible
1.11
Transaction Codes
SAP transaction codes are defined in table TSTC. Z M NN where Z Global/Local development Z Y A B C F H I L M P Q R S Global Local SAP Module Area Asset management Basis Controlling Finance Human Resource Industry Solutions Plant Maintenance Materials Management Production Planning Quality Management Project System Sales and Distribution Sequential transaction number
N
1.12
Variants
Variants (selection criteria) are program parameters. Several variants can be stored from a program to control its execution. On-line programs should always use variants to limit their execution time. Z PPPPPP NN where Z Global/Local development Z Global
Internal Use 10
PPPPPP NN
1.13
Parameter IDs
Parameter IDs are used to define default values for entry fields. The defaults are defined in the user master record. A parameter ID is linked to a field through the data element definition of the field. Z XX where Z Global/Local development Z Y Global Local Uniquely identifies the parameter ID.
XX
1.14
Jobs
Jobs are used to execute programs together that are required to complete a process or a similar function.
Job Names
Z M X.X where Z Global/Local development Z Y Global Local SAP Module Area A B C F H I L Asset Management Basis Controlling Finance Human Resource Industry Solutions Plant Maintenance
Internal Use 11
M P Q R S
Materials Management Production Planning Quality Management Project System Sales and Distribution Job name
XX
Event IDs
N(15)
1.15
Batch Data Communication (BDC) sessions are used to execute batch input of SAP transactions. XXXXXXXXXX_MMDDYY where X(10) MMDDYY
1.16
Unit test results are held on the LAN in a directory. The naming convention for the unit test file name is program.nnn, where program is the name of the program tested by the unit test case (see program naming conventions), and nnn is a sequential number (for example, 001). If a program has more than one change request, the unit test case that tests the first change would have the file type 001, while the unit test case for the second change request would have a file type 002.
Internal Use
12
1.17
Variable Names
Parameters Range Select options Working storage Constant Internal tables Local subroutine parameters Layout Set Names
{original layout set name} some names may be too large, and need to be truncated 9 Sequential program number assigned by the application team
Internal Use
13
This section defines attributes and naming standards for parameters and objects associated with the ABAP language.
2.1
Program Attributes Read only report Include module Module pool Update report K Custom program Leave blank for now Always mark this attribute
The following are the attributes for programs created in the SAP environment. Type: I I M V Status:
As the title field is the key to find the correct report at a later date, make sure you choose a meaningful description. Whenever you copy a program, make sure to change the title to help distinguish between copied versions.
Internal Use
14
2.2
Development Class
When saving a new piece of development (program or data dictionary object), a development class has to be assigned. If this new object is used only for testing purposes, and will not be transported into another environment, create it as a local private object (development class $TMP). In this way no unnecessary change requests are created. If the new object is transported to other environments, assign it to an appropriate development class (refer Appendix C).
2.3
When you assign a real development class (and not $TMP), you will be prompted for a change request number. Make sure to create a new change request for a separate piece of work. However, if a development request requires several objects to be created (such as, table, associated data elements and domains, report), put them into a single change request to avoid the risk of leaving some objects behind during a transport.
2.4 1.1.1
Internal tables should have a prefix of T_. The rest of the table name should be either the referenced physical table name or the business object. Examples: T_MATERIAL, T_MARA
1.1.2 System table addressing
The amount of detail in program comments is on the discretion of the programmer. The programmer should access the required level of program documentation to fully clarify the purpose and functionality of the program. Program documentation includes both internal and external documentation.
Internal Use
15
Program comments should appear in the documentation box, before complex code and before each FORM routine. All program comments should be clear, concise and accurately expressed, with an emphasis on the WHAT and WHY aspects. As part of this standard, all comments should appear before the coded functionality and should be in the form of a full comment line. A full comment line should not be inserted in the middle of control events (such as, IF ELSE.ENDIF) to maintain program readablility. Example: *------------------------------------------------------------------------------------------------* * This is an example of a full program comment line * *------------------------------------------------------------------------------------------------* The ABAP/4 language permits a comment adjacent to a code line. In-line comments may be used for documenting change request numbers, data element definitions and nested end statements. The change request number appears against those lines modified as part of the program enhancement. Example: MOVE:LFA1-LIFNR TO LFB1-LIFNR, example of in-line comment LFA1-NAME1 TO LFB1-NAME1.
When modifying an ABAP/4 program, lines to be deleted or changed shall be copied and commented out. All lines of code relating to the change should be commented to the right of the line with the change request number. The duplication of program lines provides a program history. Programs that have had sufficient enhancements, may be difficult to read when blocks of code are repeated and subsequently commented out. Therefore, when a program becomes too difficult to read, it should be cleaned up and prepared for another change cycle. In the following example, the number 99999 must match with the sequential number given to the corresponding program amendment. The first amendment number is numbers are incremented by one.
Internal Use
16
99999
External report or documentation can be created using the SE38 transaction, and clicking the Documentation button.
2.5
This section defines the naming conventions for program variables based on variable types. Underscores ( _ ) should be used to separate words or letters that define a variable instead of hyphens ( - ). Hyphens are only used for referencing subfields in a record string or data structure. It is recommended to reference a data dictionary field in the definition (LIKE xxx-yyy) when possible for consistency and type checking. In specific sections there are recommendations for prefixes. Prefixes are not mandatory, but make work easier for peer programmer to maintain the consistency in coding. The name always has to be meaningful. NOTE: The prefixes outlined in the following sections are reserved for those programs that follow the standards.
1.1.4 Flags
Flags are variables that contain only one of two values. These variables are defined as characters of length 1. In all cases, the following values must be complied with: = = NO, FALSE or OFF YES, TRUE or ON
All flag names should be prefixed with FL_. When checking whether a flag is TRUE, always check in this manner: IF FL FIRST REC NE SPACE. In this way, typos (such as capitals letters) do not have a negative impact.
Internal Use
17
Index variables are numeric fields used for indexing internal tables. These variable names should be prefixed with IDX_. Indexes should be defined with reference to a system table field such as SYTABIX or SY-INDEX.
1.1.6 Constant fields
Constant fields do not change during the execution of a program. Whenever possible use constants instead of hard-coding values. The constant names should be prefixed with C_.
1.1.7 Totals
When you need a variable to calculate sums, prefix the variable name with SUM_ or TOT_, SUM_ should be used for currency fields, and TOT_ should be used for calculating totals of any other fields (such as counter).
1.1.8 Structures
When you need to define a structure (record layout), prefix the name with REC_.
1.1.9 Date and time fields
Date variables should be prefixed with DAT_, and time fields with TIM_.
1.1.10 Work variables
Work variables are used for general purposes. They could belong to any variable type that is not previously discussed in this section. Work variable names should be prefixed with W_. Another option is to use G_ for global variable names and L_ for local variable names. When G_ and L_ are used, W_ should not be used in the program.
1.1.11 Parameter fields
Parameter variables are used to allow data entry at the selection screen before program execution. They have a limited length of eight characters. Parameter names should be prefixed with P_.
Internal Use
18
The SELECT-OPTIONS <field name> for <table field> statement generates a program variable used as a selection criteria. This allows a user at the selection screen to enter a range of values. The variable generated is actually a system generated table containing <variable>-lowvalue, <variable>-highvalue, <variable>-sign and <variable>-option for the table field selected. These variables have a limited length of eight characters. Variable names of this type should be prefixed with S_.
Internal Use
19
The RANGES <field name> for <table field> statement generates a program variable similar to the SELECT-OPTIONS statement. However, this variable does not appear on the selection screen. It has a limited length of eight characters. Variable names of this type should be prefixed with R_.
2.6
Messages
This section defines the naming conventions to be used for standard messaging in SAP. Standard SAP messages should be used whenever possible to eliminate redundancy. If no standard message exists, create a new message according to the guidelines described in this section.
1.1.14 Message lDs
Message IDs are 20-character names given to a group of related messages. They are named as follows:
Internal Use
20
Position 1-3 4 5 - 20
1.1.15 Message severity
Message severity defines the way the program behaves after the message is issued. The following are the message severity codes. A E W Abend Error Warning The transaction aborts and the user is unable to continue The entered data is invalid; the user must modify the data The program allows the user to override the message by pressing ENTER or to modify the data which caused the warning Displays information that may be of interest to the user Displays an informational message on the next screen
I S
1.1.16
Informatio n Success
Message number
Whenever appropriate, incorporate variables (&) in your message text. These will be filled at runtime and provide more detail.
2.7
PF Status
The PF status is a custom status bar defined to be used by a screen or interactive program to enable user actions. The following table defines the usage of standard function keys. These function keys need not be enabled, but if they are, they must comply with the standards defined in this section.
PF Key OK-Code Description
01 02 03 04 11 12 13 14
Display help screen Select entry (same as double-click) Back to previous screen List possible entries Save entries Cancel, overrides mandatory entries Print Delete
Internal Use 21
PF Key
OK-Code
Description
15 21 22 23 24
2.8
Exit, leave transaction; overrides mandatory entries First page of document Previous page Next page Last page of document
Variants define default selection entries. Variant names consist of a maximum of fourteen characters and should be descriptive. As variants are programspecific, there is no need to qualify the program name.
2.9
A batch input session name consists of a maximum of twelve characters formatted as follows:
Position Usage
I - 12
Name of ABAP by which the BDC session was created (if ABAP name consists of more than 12 characters, limit it to the first 12)
If a BDC session is created by user programmatic interface (UPI), assign the session name in the following way:
Position Usage
14 5 10 11 - 12
UPI field ICODE (transaction code) UPI field ITYPE any two character combination
Internal Use
22
2.10
Although there are no specific naming convention for modules and subroutines (forms), the names (up to thirty characters) should be meaningful. If possible, use the combination of object name and verb. For example: READ_MATERIAL CHECK_COMPANY_CODE. It is recommended to place the form routines in alphabetical order.
2.11
Batch job names will consist up to 32 characters formatted as follows: X_NNN_F_AAAA_DDDDDDDDDDDDDDDDDDD with X: NNN: F: AAAA: DDD... the one character identifier: Z the fixed three character functional name identifier for a batch job (for example, Fl, HR, ESD...) frequency code: D-Daily, W-Weekly, M-Monthly, S-SemiMonthly, Q-Quarterly, Y-Yearly, R-On Request the four character sub-application identifier, if needed, begins the description (for example, AR, CASH, PAY...) a nineteen to twenty-four character descriptive job identifier. This identifier can use alphabetic, numeric, and/or special characters. It should be as descriptive as possible.
Internal Use
23
2.12
Non-SAP production batch jobs that run with limited eight character job names follow the format below: XTTTFNNN with X: ITT: F: NNN: SBU Name The fixed three character functional name identifier for a batch job (for example, Fl, HR, ESD...) Frequency code: D-Daily, W-Weekly, M-Monthly, S-Semi-Monthly, Q-Quarterly, Y-Yearly, R-On Request Sequential number of the job stream and order. The numbering groups can have special meaning. For example: 000-099 Ad Hoc Jobs 100-1 99 Daily Jobs 200-299 Weekly Jobs 300-399 Monthly Jobs 400-499 Quarterly Jobs 500-599 Annual Jobs, etc.
This section defines the basic standards that all developed programs must comply with. The order of the components within a program must comply with the skeleton program (ZZSAMPLE, see Appendix B). This section describes the rules surrounding the use of ABAP features and components.
3.1
Program Structure
The structure of programs should follow the sample program ZZSAMPLE (refer to Appendix B). Events in this program that are not used should be removed for clarity. It is recommended to code only one statement per line. This allows for easier deleting, commenting and debugging. Comments should be inserted: At the beginning of the program (to outline the general functionality) Before each major section (MODULES, FORMS) To clarify complex or unclear logic Before SELECT statements
Internal Use
24
3.2
The main documentation block contains a detailed description of the program, maintenance history and tables referenced. A sample documentation block is included in the sample program ZZSAMPLE (see Appendix B). These are the entries required in the main documentation block: Program name and title Author and creation date Purpose of the program Input/output parameters SAP tables used; for each entry define: input, output or both External files accessed; for each define: input, output or both ADR Name
For each modification, an entry has to be created in the maintenance block with the following information: Development request number (ADR) Date of change Programmer name Description of change
3.3
Modularity
All repeated code or common processes should be coded in subroutines (forms). This enhances the readability and maintainability and makes the debugging process easier. Calls to function modules should be used whenever available.
3.4
Statement Formatting
Indent all statements for easy reading. Make sure you align IF, THEN and corresponding ENDIF statements. Aslo align CASE, DO, WHILE, etc. statements. This can be easily achieved by using the pretty print utility in the editor.
3.5
Parameters and select-options should be defaulted (for example, company code, default date to todays date). This will prevent that the report is accidentally started for all data.
Internal Use
25
IMPORTANT: Have the process team determine what selection fields can be made mandatory, and whether it is a viable option to allow a single value entry versus a range. These are very important considerations for the production system, as starting a report with a wide selection range can result in serious performance issues.
3.6
All user input has to be validated. This is especially the case for module pools. Make sure a meaningful error message is displayed in case the user enters a wrong value. If the referenced data dictionary field has a check table assigned, and no validation is coded, the general message 058(00) Entry & does not exist ... should be displayed.
3.7
Messages
All messages should be implemented through message numbers. Any text messages and constant screen text should be implemented through numbered texts. This will ensure portability to another language.
3.8
Data Access
Never use native structured query language (SQL) within ABAP programs (EXEC SQL ... END-EXEC). This would circumvent SAP data dictionary checks and corrupt system integrity. Due to performance reasons the use of logical databases should be carefully evaluated. The huge amount of overhead in the logical database programs often has a negative impact on runtime behavior.
Internal Use
26
After every table access, the return code needs to be checked to determine whether the access was successful. If no records could be retrieved, an appropriate message should be displayed.
3.9
Data Update
SAP database tables are to be updated only through SAP provided code to ensure data integrity. This can be ensured through the use of existing SAP programs or through the use of BDC driven screen processing.
3.10
The structure of an external file should be defined in the data dictionary as a structure. This will simplify maintenance especially if the same external file is used in several programs.
3.11
Authorization Checking
When data is accessed using a logical database, SAP handles authorization checks automatically. However, when data is retrieved using SELECT statements, the programmer has to incorporate appropriate authorization checks in the developed code. Example: Authorization object M_ISEG_WIB (plant authorization for inventory documents) has the fields ACT\/T (activity) and WERKS (plant). AUTHORITY-CHECK object MISEGWIB Id ACTVT field 03 id WERKS field w werks. IF SY-SUBRC NE 0. EXIT. ENDIF.
Internal Use
27
Refer the online help for details on the AUTHORITY-CHECK statement. The requirements for authorization checks is formulated by the process teams (supported by the security team) and documented in the development specification form. The developer determines the appropriate authorization object with assistance from the security team. When possible, checks should be performed at selection screen level before any data is retrieved (for example, authorization for a specific company code). At this point, it is not planned to grant end-users access to transaction SA38. Therefore, transaction codes are created for all reports, which are run online in the production environment. The security team then authorizes appropriate users to execute those report transactions.
3.12
Lock Objects
When objects are modified, locks have to be issued through standard SAP locking mechanism. For custom created objects, the corresponding lock objects should be created beforehand to achieve this.
3.13
Debugging
Make sure that all hard-coded break-points and testing code (for example, additional output) are removed before the program is moved to the production environment. It is recommended to set soft break-points at runtime instead of hard-coding them into the program.
3.14
Use the SORTED clause only when: there are less than 100 rows rows are already in sorted order
If an internal table must be sorted and the above criteria are not met, fill the table in unsorted order and then sort specifying the key fields. Also, consider the use of a sorted table.
1.1.18 ASSIGN
Use of field symbols should be avoided unless necessity dictates. When used, field symbols have to be documented when defined and used.
Internal Use
28
Code only one condition per line for legibility. Use parentheses to group conditions. Instead of nested IF statements, use CASE statements whenever possible as this enhances readability, maintainability and performance.
1.1.20 DATA
Define variables within the DATA statement in accordance with program variable names (see section 2.5, Program variable names). Align variable definitions in a readable and consistent format. Whenever possible, define variables by LIKE <data dictionary field>. This allows for consistent field definitions. If this is not possible, always define the data type and length; never rely on defaults. Although ABAP initializes all fields at program execution, it is recommended to initialize variables using the CLEAR statement. Always clear data structures and variables before repopulating, especially in program loops. This is required in function modules, as multiple calls to the same function module during one program execution will not refresh the function module variables. CHECK, EXIT, REJECT, STOP Use these statements to suspend processing and/or skip remaining unnecessary processing for improved performance. MOVE-CORRESPONDING This statement should be avoided. If used, care should be taken since only fields with identical names are moved. To move a data structure to an equivalent structure, use <target-structure> = <source-structure>. READ TABLE When reading a table with the WITH KEY option, ensure that the key is filled from the leftmost field in the table. This is most efficient with the use of BINARY SEARCH addition. Note: In order to use the binary search, the table has to be sorted. SORT Always specify the sort fields for the SORT statement for legibility and maintainability, including when the system default is used.
Internal Use
29
Declarative Elements The term Declarative Elements describes those available ABAP/4 elements that are necessary to define the internal environment under which an ABAP/4 program is run. As part of this standard, each new ABAP/4 program shall only include those declarative elements required for the program in accordance with program specifications. Throughout all the declarative elements defined for an ABAP/4 program, the exact level of indentation is not enforced, but the level of consistency is (that is, declarative elements can be indented 3 or 5 characters, etc., but the indentations should be kept consistent). Also at least one blank line shall separate each new declarative element. The following declarative elements are described below. REPORT TABLES TEXTS SELECT-OPTIONS PARAMETERS DATA FIELD-GROUPS FIELD-SYMBOLS
REPORT Element The REPORT element shall start in column one in the line after the comment box, with any associated parameters consistently indented to the right of the REPORT element. The NO STANDARD PAGE HEADING parameter must be included for those ABAP/4 programs that produce report(s) as output. Example: REPORT ZFIOOO1A NO STANDARD PAGE HEADING LINE-SIZE 132 LINE-COUNT 65 MESSAGE-ID ZZ
Internal Use
30
To use the MESSAGE option in the ABAP to send messages back to the user, you must first define the message to the message table T100. Hard-coded messages should be avoided. TABLES Element The TABLES element shall start in column one with all the tables declared in the subsequent lines. Each table commences on a new line and is consistenly indented and documented. The ordering of table declaration is not enforced as part of this standard. Example: TABLES: MARA, MARC, MARD, MARM, Material Master Mat Master C segment (Plant data) Mat Master D segment (Storage Locations) Material UOM Table
SELECT-OPTIONS Element The SELECT-OPTIONS element shall start in column one with all the selectoptions declared in the subsequent lines. Each select-option commences on a new line and is consistently indented. It is recommend to use the prefix S for SELECT-OPTIONS. Example: SELECT-OPTIONS: S_USERID S_DOC_DATE PARAMETERS Element The PARAMETERS element shall start in column one with all the parameters declared in the subsequent lines. Each parameter commences on a new line and is consistently indented. It is recommend to use the prefix P for PARAMETERS. Example: PARAMETERS: P_USERID LIKE P_DOC_DATE SY-UNAME, comment LIKE SY-DATUM. comment FOR SY-UNAME, comment FOR SY-DATUM. comment
Internal Use
31
DATA Element The DATA element shall start in column one with all the data work fields declared in the subsequent lines. Each data work field begins on a new line and is consistently indented. The data work field type and value definitions should also be aligned. The only exception could be for structure definition utilizing the INCLUDE STRUCTURE format (see below). As part of these programming standards, wherever possible the reference to data dictionary fields and structures should be used by the programmer when developing ABAP/4 programs. The ABAP/4 programming language offers many benefits with the available commands and statements when data dictionary fields are referenced. It is due to this reason the LIKE attribute should be used to define work fields, where possible, under the data element area of the program. Data work field naming conventions is not enforced in these programming standards, although meaningful assignment of names is necessary. * Example: DATA: USERID DOC_DATE DTL_RPT LIKE LIKE SY-UNAME, SY-DATUM, comment comment comment Individual Work Fields
TYPE C DEFAULT Y,
* exception) Example:
Internal Use
32
Examples: DATA: BEGIN OF USERIDS OCCURS 50, CODE(5), NAME LIKE SY-UNAME, ACCT(10), END OF USERIDS. DATA: BEGIN OF DATE, MONTH(2) DAY(2) YEAR(4) TYPE C, TYPE C, TYPE C,
END OF DATE. FIELD-GROUPS The FIELD-GROUPS element starts in column one with groups defined in the subsequent lines. The first field-group is always HEADER (available sort fields), followed by the remaining groups which must be meaningfully named. The INSERT statement required to insert field name into each field-group immediately follows the FIELD-GROUP declaration. Each new INSERT statement also starts in column one and has the first field name indented. The fields to be inserted references those corresponding data dictionary names where possible. This makes coding benfits available with several of the ABAP/4 command statements. Examples: FIELD-GROUPS: HEADER DETAIL INSERT: LFA1-LIFNR LFA1-LAND1 INTO HEADER INSERT: LFA1-STRAS LFA1-ORT01 INTO DETAIL
Internal Use
33
FIELD-SYMBOLS element The Field-Symbols element starts in column one with field-symbols indented on the subsequent line(s). Each field-symbol should be assigned a meaningful name. Examples: FIELD-SYMBOLS: <ACCT_CD>, <STORE_LOC>. Event Elements The ABAP/4 language has several programming events. Each programming event signals the execution of a specific set of program statements (block of code), at a specific point during a program run time. The following event elements are described here. INITIALIZATION START-OF-SELECTION / END-OF-SELECTION GET / GET LATE and other DB access related statements TOP-OF-PAGE
Internal Use
34
This event is always present for ABAP/4 programs with a selection screen. It is essential that this event always occurs prior to the Start-of-selection event. Be careful with regard to the programming logic contained in this event, as the Initialization event is not executed in batch. Data declarations are not defined after this event. This is because the program does not recognize data fields during batch execution
START-OF-SELECTION / END-OF-SELECTION
The events Start-of-Selection and End-of-Selection should be present in all ABAP/4 reporting programs. The End-of-Selection event is used to execute, among other things, the standard FOOTER (if applicable), so that end of report (footer) detail lines are printed. Note: It is recommended that the files be accessed through singular select statements to the database tables. Access to logical databases through GET logic should be kept to a minimum due to the load they place on the system.
GET / GET LATE and other DB access related statements
The event GET LFA1 accesses the table LFA1. As part of these standards, the GET event should only be used with a database table. It should be used in conjunction with a table that requires specific processing. Example: (Non Standard) GET LFA1. GET LFB1. CHECK LFB1-BUKRS = US00. WRITE: / LFB1-EIKTO. (Standard) GET LFB1. CHECK LFB1-BUKRS = US00. WRITE: / LFB1-EIKTO. To uniquely identify the source of the data field, all the table fields accessed and subsequently referenced in an ABAP/4 program has the field prefixed with its table name. The exception to this is the use of table fields in connection with the ATENDAT construct.
Internal Use
35
The ABAP/4 language allows program data fields, which are unique to the program, to be referenced without a prefix. Example: LFB1-BUKRS, (Standard) BUKRS,
TOP-OF-PAGE
(Non Standard)
A function module should be written to control all header and footer detail lines for all ABAP/4 report generating programs.
Control Events
Controlling events within the ABAP/4 environment are used to control the flow of the program within processing blocks. There are several controlling elements available, and their description and functionality are described below. IF.ELSE..ENDIF DO.ENDDO / WHILEENDWHILE CASE..WHEN.ENDCASE ON CHANGE OF.ENDON LOOP..ENDLOOP LOOP TERMINATION TERMINATION OF PROCESSING SUBROUTINES FUNCTION MODULES IF..ELSEENDIF
Internal Use
36
When coding nested IF statements within a program, limit the structure to three nests. For other cases use a PERFORM call or CASE statement execution. This restricts lengthy control events congesting a program, which makes reading difficult. Each matching IF..ELSE.ENDIF should be consistently aligned and indented. Every IF statement should include an ELSE statement. Example: IF BKPF-BELNR = INVOICE_NUMBER. PERFORM PROCESS_INVOICE. ELSE. PERFORM CHECK_DOCUMENT_NO. ENDIF. When a program variable is repeatedly evaluated for discrete values, the IF.ELSE.ENDIF statement should be replaced with the CASE..WHEN.ENDCASE construct. Example: 1 (Non Standard) IF LFB1-EIKTO = 00014000. <.CODE.>. ELSE. IF LFB1-EIKTO = 00014500. <CODE.>. ELSE. IF LFB1-EIKTO = 00014800. <.CODE.>. ELSE. IF LFB1-EIKTO = 00015000. <.CODE.>. ENDIF. ENDIF. ENDIF.
Internal Use
37
Example: 2
(Standard) CASE LFB1-EIKTO. WHEN 00014000. <.CODE.>. WHEN 00014500. <.CODE.>. WHEN 00014800. <.CODE.>. WHEN 00015000. <.CODE.>. WHEN OTHERS. <.CODE.>. ENDCASE.
IF..ELSEIF When possible use the Case statement as a substitute for the If..Elseif construct. The case statement makes the code clearer. DOENDDO / WHILEENDWHILE The Do.Enddo / While.Endwhile control events is always coded with a controlled exit point. Example: DO 9 TIMES. SHIFT NAME BY 1 PLACES. ENDDO. OR DO. READ DATASET SAPV01 INTO RECORD. IF SY-SUBRC NE 0. EXIT. ENDIF. ENDDO.
Internal Use
38
CASEWHENENDCASE When coding nested CASE.WHEN.ENDCASE statements within a program, limit the structure to three nests. At such a point a PERFORM call could be executed. The WHEN OTHERS clause could be used more often. This restricts lengthy control events congesting a program, which makes reading difficult. Each nest CASE..WHEN.ENDCASE statement should be consistently aligned and indented. For program efficiency, the most likely WHEN event should be coded first. Example: See the control event example for IF..ELSE.ENDIF ON CHANGE OFENDON The ON CHANGE OF control event is preferred to the IF statement when field change evaluation is required. This eliminates the need to define a work field. Example: GET LFA1. ON CHANGE OF LFA1-LIFNR. WRITE:/Vendor name:, LFA1-NAME1. ENDON. LOOP.ENDLOOP To ensure that all requested entries in a transparent table are read, the table should be initialized to spaces. ABAP/4 interprets each value (other than space) in a declared transparent table as part of the generic key, and hence no data is processed. Example: MOVE SPACE TO T005. LOOP AT T005. <.CODE.>. ENDLOOP. LOOP TERMINATION For readability and maintainability, loop termination should be controlled through the CHECK and EXIT statements.
Internal Use 39
Example 1:
Example 2:
TERMINATION OF PROCESSING The REJECT or CONTINUE statement is used to terminate a processed Table and all dependent Tables lower in the logical database hierarchy. The STOP statement is used to terminate an ABAP/4s data selection. The ENDOF-SELECTION event is declared in all programs and is used in conjunction with the STOP statement. The inclusion of the END-OF-SELECTION event is consistent with the rule of structured programming of one entry and one exit point. SUBROUTINES The use of subroutines is imperative in developing well structured programs. Wherever possible a program should logically organize command statements into subroutines. The ABAP/4 statements FORMENDFORM are used to define the boundaries of a subroutine. Both of these statements start in column one, with subroutine statements indented consistently thereafter. Each subroutine should be prefixed with a standard FORM comment box. All FORM.ENDFORM constructs should be placed at the bottom of the program, ordered according to their execution sequence. An ABAP/4 program should not call a FORM routine in another program. In such a situation, the program code that is common to two or more programs is incorporated into an INCLUDE member or a FUNCTION MODULE. The programmer, where possible, should refrain from duplicating ABAP/4 code across programs. Example: *------------------------------------------------------------------------------------* * FORM Read-purchase-order * *------------------------------------------------------------------------------------*
Internal Use 40
*This form reads the purchase order relating to the invocie * *document stored in the internal table INV-DOCS. * *------------------------------------------------------------------------------------* FORM READ_PURCHASE_ORDER. IF MOVE.. ENDIF. ENDFORM. Operation Events Operation events are program events indicated by an operational action (such as, MOVE, SUM, APPEND, WRITE,etc.) MOVE-CORRESPONDING / ADD-CORRESPONDING Fields participating in these special ABAP/4 statements, should, where possible, use the LIKE statement. Examples: START-OF-SELECTION. GET LFA1. MOVE-CORRESPONDING LFA1 TO RECORD. GET LFB1. MOVE-CORRESPONDING LFB1 TO RECORD. ------END-OF-SELECTION.
3.15
When changing an existing program, the maintenance block must be updated. Refer to the sample ZZSAMPLE for more information (see Appendix B). Every line has to be marked with a right-justified comment (use either the request number or your nameinitial of first name, followed by the last name along with the date the change was applied). Never change or delete an existing line. If a statement has to be deleted, comment it out. If a statement has to be modified, comment out the existing line and add a new line.
Internal Use
41
If a major block of code is inserted or deleted, it is acceptable to mark the block with: Begin of insertion/deletion TKuhn 12/06/1997 End of insertion/deletion TKuhn 12/06/1 997
This section describes some miscellaneous programming techniques that are part of the programming standards. Not all techniques are described here; nevertheless we encourage the use of the recommended programming techniques where appropriate.
Data Selection
When an ABAP/4 program is executed, it reads the selected data from the relevant databases based on evaluations as per report specifications. Therefore, consideration should be given to the controlled restriction of unwanted database accesses. Use of precise specifications within all programs significantly enhances program performance. The ABAP/4 language permits specification to multiple statements on one physical line of coding. To enhance program readability, each ABAP/4 statement should be coded on an individual line. The practice of chaining identical ABAP/4 statements can increase program readability and remove redundant statements. Large processing blocks of code should be broken down into logical units of work and performed as subroutines. Well structured programs that are developed using subroutines are easier to read and maintain. Subroutines are ordered in the sequence of system execution, to aid in program reading. The programming standards support the readymade key work structures available in the ABAP/4 language. In the SAP ABAP/4 editor SE38, you can insert a template for each function call. This is done by first placing the cursor on the line where the code has to be inserted, and then pressing the "Insert Statement" button. Then, select the desired function. Frequently used statements should be defined with a VALUE clause in the DATA declaration area. Frequently used data declaration structures should be defined as Include programs. Programs that contain arithmetic computations should be set as 'FixedPoint Arithmetic' in the program attributes. Fixed-Point arithmetic performs computations of an ABAP/4 program similar to a standard calculator.
Internal Use 42
Program debugging and maintenance is made easier by setting this attribute. All numeric fields used in calculations should be setup as packed. Numeric fields are stored as packed in the database. Calculations are performed on packed fields. For incrementing numeric field values, use this syntax: FIELDA = FIELDA + 1. Use internal tables as work areas for database tables, when practical. Reference tables that are used repeatedly in a program are candidates are loaded into ABAP. If all the fields are required, use the STRUCTURE syntax. Otherwise, name each field in the internal table with the database field name, and use the LIKE construct to define attributes. Use the MOVE-CORRESPONDING statement to load the table unless the entire table has to be loaded. In that case use SELECT. INTO. Use the STRUCTURE syntax, since the structure of the internal table must be identical to database. Be as restrictive as possible with the WHERE clause to reduce the answer set. Use ORDER BY to obtain an order that is different than the sequence of the key. Make the estimate of the size of the internal tables as accurate as possible (OCCURS). Overestimation causes excessive memory to be allocated. Underestimation causes the table size to be incremented four times. Doubling each time then causes the remainder of the table to be paged to disk if the estimate is exceeded. The former is uneconomical and the later causes performance degradation.
Internal Use
43
Include Reports
Include Reports should be defined to an ABAP/4 program on position one. This allows the explosion of 'Include' reports by using the character '>' on the editor line. If an Include Report is updated, all subsequent programs containing the Include Report automatically updated. The line between an Include Report and the main program is not dynamic when SAP naming standards are not followed. If nested Include Reports are in effect, each subsequently linked report should be updated, all the way up to the main program. Common Data Parts should be created as Include Reports for ease of maintenance The system return code (SY-SUBRC) must be analyzed after performing all the data retrievals
Flags
Function modules in ABAP/4 development environment are used to execute common processing logic available to all programs. Function modules are modules that are developed through SAP's Function Module Maintenance environment. These modules are designed for reuse and should be built in a generic fashion such that they perform basic but repetitive functions (such as, Field Validations). Function module should be setup such that the programmer is insulated from the processing necessary to complete the task. Data is imported and exported into the function module through parameter statements used during function calls. Hence, function modules should be considered to resolve complex efficiency issues. The code is maintained in a central location, increasing reusability and simplifying programming. Exceptions defined in the interface should describe all possible error situations. You should decide whether the calling program handles an error itself or the function module handles the error.
Internal Use
44
All declarative elements defined in a function module should be consistent with the standards and comments described in this document. The programming elements permissible in the function module environment should also conform to the programming standards specified in this document.
Internal Use
45
* Output parameters:
Date Request#
* TABLES TABLES:
Work fields Totals Flags Indexes Ranges Structures Internal tables * CONSTANTS: * * * * * * * * *
* INITIALIZATION
* * * * * * * * * * * * * * * *
* * * * * * * * * * * * * * * * * * * * * * *
Internal Use 48
INITIALIZATION. * AT SELECTION SCREEN * AT SELECTION SCREEN. *START-OF-SELECTION START-OF-SELECTION. * END-OF-SELECTION END-OF-SELECTION. * TOP-OF-PAGE TOP-OF-PAGE. * END-OF-PAGE END-OF-PAGE. * AT USER-COMMAND AT USER-COMMAND. * AT LINE-SELECTION AT LINE-SELECTION. * FORMS
The following items should be checked during the review: Does the specification conform to the guidelines set forth Are all mandatory sections filled in
All record layouts, inputs and outputs must be documented. Existing documentation, if any, should be referred. Abnormal conditions must be addressed. The review team must decide whether a follow up review is required.
CODE REVIEWS
Code reviews are required for application development. Code reviews are held to inspect code for correctness and efficiency. It is an ideal way to help educate the programmers to a new application or coding language. It also helps keep the code consistent with the standards of program development. The following is a list of participants in a code review and their responsibilities: Author of the program code: Schedules the code review Distributes code prior to review Documents the MoM Corrects code as needed Reviewers 2 to 3 programmers including 1 SAP ABAP experienced programmer Review code prior to meeting Note any deviation from guidelines
Internal Use
50