View
839
Download
96
Category
Preview:
Citation preview
8/8/2019 37719530 ABAP Programming Standards
1/33
ABAP Programming Standards - 4.XContents
Contents.............................................................................................................2Document Control Sheet.....................................................................................5Introduction.........................................................................................................6SAP Object Naming Conventions.........................................................................7
1. Programs, Functions, Includes and Reports...................................................72. Module Pools and Module Pool Includes........................................................83. Function groups.............................................................................................94. Function modules..........................................................................................95. Transaction Codes.......................................................................................106. Development Classes..................................................................................107. Logical Databases.......................................................................................108. Maintaining SAP Standard Objects..............................................................109. Data Dictionary...........................................................................................1110. Authorizations.............................................................................................1211. Profiles........................................................................................................13
Programming Standards...................................................................................151. One Command One Line:............................................................................152. Pretty Printer:..............................................................................................153. Variables.....................................................................................................164. Parameters ( P_ ).........................................................................................165. Parameter used as checkbox ( PX_ )and (RB_)for parameter used as radio-button
166. Select-options ( S_ ).....................................................................................167. Ranges ( R_ )...............................................................................................168. Constants (C_ )............................................................................................179. Counters ( N_).............................................................................................1710. Internal table (IT_) for Standard tables, (IS_) for Sorted tables, (IH_) for hash tables
1711. Structure ( X_ )............................................................................................1812. Flags ( FG_ )...............................................................................................1913. Error Messages............................................................................................1914. Subroutines.................................................................................................2015. Literal Text:.................................................................................................2116. PF-Status.....................................................................................................2217. External Files...............................................................................................2218. Variants.......................................................................................................2219. Messages....................................................................................................2320. Report Formatting.......................................................................................2321. Batch Data Input.........................................................................................2322. Authorization Checking...............................................................................2323. Lock objects................................................................................................2424. Debugging...................................................................................................24
Code Documentation........................................................................................25Optimization......................................................................................................27
1. Avoid Dead Code:........................................................................................272. Logical Database:........................................................................................273. Techniques for efficient Database selection................................................274. Internal Tables............................................................................................375. If Condition:.................................................................................................406. Case Statement:..........................................................................................407. ABAP Statements........................................................................................408. Describe Statement:....................................................................................419. Field Length:...............................................................................................4110. Arithmetic Operators...................................................................................4111. Use of tables...............................................................................................4112. WHERE clause.............................................................................................4113. Aggregate functions....................................................................................4114. Join..............................................................................................................42
8/8/2019 37719530 ABAP Programming Standards
2/33
15. Not Operator...............................................................................................4216. Minimizing the database load......................................................................4217. Standards for Specific Statements..............................................................4218. Coding Tips.................................................................................................42
ABAP Module Pool Standards and Practices......................................................431. Program Structure.......................................................................................432. Screen Definitions.......................................................................................433. GUI interfaces..............................................................................................434. POP-UP windows..........................................................................................43
5. OK_CODE (SY-UCOMM)................................................................................446. Update........................................................................................................44NULL VALUES....................................................................................................44INDEXES............................................................................................................45BUFFERS...........................................................................................................46ABAP Objects....................................................................................................48Appendix A : Table of Application Area Code....................................................53Appendix B : Standard Program Structure........................................................54Appendix C : Business Short, Medium, Long Names.........................................57Appendix D : Template Screen Flow Logic Structure........................................58
VersionDate of IssuePrepared byNameDesignation/Role-DepartmentEmail IDSignature
Reviewed byNameDesignation/RoleEmail IDSignature
Approved byNameDesignation/Role-DepartmentEmail IDSignature
Issued/ Base-lined byNameDesignation/Role-DepartmentEmail IDSignature
After completion of each review cycle, configuration manager must increment the version number.The document history is available with the Software Quality Assurance department.
Document HistoryVersion No.Date of IssueLocation of ChangeDescription of the Change
IntroductionThe ABAP language is an "event driven". The ABAP processor controls the execution of an event. For example, the
event AT-SELECTION-SCREEN is executed when the user hits ENTER on the selection screen and the event START-
OF-SELECTION is executed when the user presses PF13 to start the program. Because the ABAP languageincorporates many "event" keywords and these keywords need not be in any specific order in the code, it is wise to
implement in-house ABAP coding standards.
This document contains a list of possible ABAP coding standards, as well as some efficiency standards.Note: Customer supplied ABAP standards, if any, for a project takes precedence over this document. However, if there
are no coding standards supplied by the customer, Intelligroups standards shall be used for the project. Also, if any partof the document is not relevant to the project, considering the nature of the project, then all those sections relevant to the
project shall be adhered to. The programming standards being used shall be referred to in the project plan for the project.
SAP Object Naming ConventionsThis section defines the naming conventions for the following object types found in the SAP environment:
Programs, Functions, Includes, and Reports
Module Pools, Module Pool IncludesFunction Groups, Modules
Transaction Codes
Development Classes
Logical Databases
SAP Standard objects
Data Dictionary elements
Programs, Functions, Includes and ReportsThis section defines the naming conventions to be used by ABAP programs, functions, includes, and reports created in
the SAP system. Refer to Maintaining SAP Standard Objects (Section 2.1.7) if you are modifying a SAP standard object
Object names will consist of eight (8) characters formatted as follows:
Position Description
1 Usage: "Y" Tools and Utilities that are not to be migrated to production.
8/8/2019 37719530 ABAP Programming Standards
3/33
"Z" Application programs that will be moved to production.
2 SAP Application area (Ref. Appendix A)
4 -7 Type of program:
FUNC for function programs
"REPT" For Report programs, interactive report programs
BDCP for BDC programs BOLT for Bolt on Programs
SCRP for Script driver programs
INCL" For Include Module
MODP for Module pool programs
SUBP for Subroutine pools
INTP for Interface pools
CLSP for Class pools
9-27 should be a meaningful description for the program.
29-30 Reserved for future use/versions.Report and update program include object names will consist of eight (30) characters formatted as follows:
Position Description1 Z Required by SAP
2-7 Same as positions 4-7 in program name
9-23 Should be a meaningful description for the include
25-27 Usage:
"TOP" Data Declarations, Tables, etc.
PAI for PAI Modules
PBO for PBO modulesFnn; for Subroutines (Forms)Where "nn" is a numeric integer between 00 and 99.
The following is an example customer program for the application area M, and the appropriate includes:Program name ZM_REPT_DISPL_MATERIAL_LIST_01
Data include ZM_INCL_ MATERIAL_LIST_TOP_01
Form routine include ZM_INCL_ MATERIAL_LIST_F01_01
Module Pools and Module Pool IncludesThis section defines the naming conventions to be used for module pools and module pool includes created in the SAP
system. Module Pool names will consist of thirty (30) characters formatted as follows:
Position Description
1-3 "SAP" - This is the SAP standard
4 Module pool type:"M" - Screen Module pool
"D" - Dialog Module pool
U" - Update Module pool
"F" - Subroutine Module pool
5 "Z" - Indicates a user defined module
6 Application Area (Ref. Appendix A)
7-27 User defined; should be meaningful for the application preferably the
Transaction codeModule Pool Include object names will consist of thirty (30) characters formatted as follows:
Position Description
1 Module pool type:
"M" - Screen Module pool
"D" - Dialog Module pool"U" - Update Module pool
2-22 User defined; should be meaningful for the application preferably the
Transaction code
24-26 Usage:"TOP" Data Declarations, Tables, etc.
PBO; PBO modules
PAI; PAI modules
Fnn; Subroutines (Forms)
Where "nn" is a numeric integer between 00 and 99.
The following is an example customer module pool for the application area M, and the appropriate includes:
Program name SAPMZMZ_MAT_LIST
8/8/2019 37719530 ABAP Programming Standards
4/33
Data include MZ_MAT_LIST_TOP
Form routine include MZ_MAT_LIST_F01
PBO include MZ_MAT_LIST_PBO
PAI include MZ_MAT_LIST_PAI
Function groupsThis section defines the naming conventions to be used for function groups. Function group names of twenty six (26)
characters formatted as follows:
Position Description
1 "Z".
2 Application Area (Ref. Appendix A)
User defined; should be meaningful for the function group
Function groups should contain related function modules and have the global interface flag turned off.Function modules
This section defines the naming conventions to be used for function modules. Function module names are recommended
to be very descriptive. The following is a suggested naming convention:
Position Description
1 "Z" required by SAP
3 Application Area (Ref. Appendix A)
4-30 Use descriptive words, separated by underscores
Function modules should always reference data dictionary structures in the interfaces for export, import and tables. Thi
is mandatory if the function module being created is to be used for RFC interfaces.Transaction Codes
This section defines the naming conventions to be used for transaction codes (TCODE) created in the SAP system
Transaction code names will consist of Twenty (20) characters formatted as follows:
This section defines the naming conventions to be used for function groups. Function group names of twenty-six (26)
characters formatted as follows:
Position Description
1 "Z".
2 Application Area (Ref. Appendix A)
4-20 User defined; should be meaningful for the function group
Development Classes.
This section defines the naming conventions to be used for development classes DEVC stored in the TDEVC tableDevelopment classes are used to pool related SAP objects into one common area for easier reference. Development class
names will consist of Thirty (30) characters formatted as follows:
This section defines the naming conventions to be used for function groups. Function group names of twenty six (26)
characters formatted as follows:
Position Description
1 "Z".2 Application Area (Ref. Appendix A)
4-27 User defined; should be meaningful for the function group
Logical Databases.This section defines the naming conventions to be used for logical databases created for use with ABAP programs
Logical database names will consist of twenty (20) characters formatted as follows:
Position Description1 Usage:
"Y" Tools and Utilities that are not to be migrated to production.
"Z" Application programs that will be moved to production.
2 Alphanumeric identifier (0 - 9, A - Z)
3 Application Area (Ref. Appendix A)
4 - 14 Meaningful Alphanumeric identifier
15 - 20 Reserve for future
Maintaining SAP Standard ObjectsThe purpose of this section is to define the naming conventions to be used whenever working with SAP standard objects
SAPS delivered objects are not to be modified. User exits should be used whenever possible or address modifications via
8/8/2019 37719530 ABAP Programming Standards
5/33
the customizing facilities provided.
If a SAP standard object is to be modified, the object(s) must be copied and renamed. The copied object can then be
maintained and substituted in the program path.
For functions, includes, and reports, the first position is to be changed to "Z". For Module Pools and Module Pool
Includes, change the 5th position to a "Z". The purpose of this procedure is to ensure that all SAP delivered code remain
intact as well as identifying all program customizations when migrating to a new release.
In the event ABAP programs, that the above is not possible, Include modules must be added to where the customizedcode must be called. The include module must indicate (in the documentation) its purpose and location where it is called
from.
Data DictionaryTransparent tables.Position Description
1 Y,Z or T9
2 Application identifier3 - 16 meaningful description
ViewsViews are virtual tables. The length of the view names can be sixteen (16) characters.
Position Description
1 Y, Z or T9
2 Application identifier
4 - 8 VIEW9 - 16 meaningful name
StructuresThe following naming convention is to be used for structures, by position:
Position Description
1 Z, Y, T9 required by SAP2 Application identifier
4 -10 STRUCT11 - 30 Meaningful description
Domains
Domains define the physical attributes of a field. Domains can be checked against value tables or be assigned a checktable depending on the usage for the domain. Domain names should be six (6) characters long and are to be defined by
the following naming standards by position:
Position Description1 Z & Y
2 Application identifier
4 - 7 DOM
8 - 30 Meaningful name
Example:
ZM_DOM_MATERIAL
Data ElementsData elements define the description for a field (Semantic domain). Data elements are to reference a corresponding
domain that matches the physical requirements for that element. Data element names should be six (6) characters long
and are defined by the following naming standards by position:
Position Description
1 Z, Y or T9
2 Application identifier
4 - 7 DEL
8 - 30 Meaningful name
Example:ZM_DEL_MATERIAL
Fields
8/8/2019 37719530 ABAP Programming Standards
6/33
Fields are to be descriptive and should not exceed 6 characters. Long field names are cumbersome from a programming
perspective. It is recommended that the field name be named according to the associated data element in the following
convention.
However SAP allows up to 30 characters for field names.
AuthorizationsObject Class
An authorization object class, groups common check objects together in a logical group. Authorization class has a lengthof four (4) characters and should be defined as follows:
Position Description1 Z
2-4 3-character short business name
Check objects (Authorization Objects)Check objects are objects that are called from ABAP to check the login users authority to perform a function or check
access to specific field values.
Naming convention:Position Description
1 Z Required by SAP
2 Application area (Ref. Appendix A)
3 _ underscore
4-10 Use meaningful words
Application AreaAuthorizations control the values of a specific check object for which a user is to have access to. A value or range of
values is assigned to each field based on the authorization. The second character for any authorization must not be an
underscore _, this is reserved by SAP.
Naming convention, suggested for consistency with check objects:
Position Description
1 Z Suggested by SAP
2 Application area (Ref. Appendix A)
3 _ underscore4-10 Use meaningful words
Alternative naming convention (Release 2.2):
Position Description1 Application area (Ref. Appendix A)
2 : Colon
Use meaningful words
ProfilesProfiles link multiple authorizations into one common group, usually defined as a business profile. A business profile is
assigned specific authorizations to perform tasks related to the security level of that business profile. The second
character for any profile must not be an underscore _. This is reserved by SAP.
Naming convention, suggested for consistency with check objects:
Position Description
1 Z as suggested by SAP
2 Application area (Ref. Appendix A)
3 _ underscore4-10 Use meaningful words
Alternative naming convention (Release 2.2):
Position Description
1 Application area (Ref. Appendix A)
2 : colon
Use meaningful words
Programming StandardsOne Command One Line:
Each ABAP command consists of a sentence ending with a period. Multiple commands can be on one line; however, a
a standard start each new command on a new line. This will allow for easier deleting, commenting, and debugging.
8/8/2019 37719530 ABAP Programming Standards
7/33
Pretty Printer:The ABAP editor has a PP (Pretty Printer) command to indent by 2 positions specific lines of code and add subroutine
comments. Event keywords are typically not indented. This command is CPU intensive, therefore, do not overuse it.
TYPES: BEGIN OF IT_TAB,
F1 TYPE sg-field1,
F2 TYPE sg-field2,
END OF IT_TAB.
DATA: TAB TYPE STANDARD TABLE OF IT_TAB WITH HEADER LINE.
DATA: f1 TYPE I,f2 TYPE I.
START-OF-SELECTION.
IF f1 = f2.
f1 = 0.
ELSE.
f1 = 1.
ENDIF.
SELECT * FROM tabl
WHERE field1 EQ sg-field2
AND field2 BETWEEN sg-field5 AND sg-field6.MOVE ...
APPEND ...
ENDSELECT.
END-OF-SELECTION.
LOOP AT tab.AT NEW f1.
CASE F1.
WHEN ...WRITE:/ ...
WHEN ...
WRITE:/ ...
ENDCASE.
ENDAT.
WRITE:/ f1,
f2,
ENDLOOP.
VariablesABAP variable names can be up to 30 characters for DATA fields and subroutines and up to 8 characters for SELECT-
OPTIONS and PARAMETERS, therefore, as a standard make the names descriptive. Since SAP segment/table-field
names are hyphenated with a '-', use an '_' to hyphen program-specific variables. Whenever possible, TYPE paramete
should be used to define work fields.Ex. DATA: V_MATNR TYPE MARA-MATNR.
All program variables should use the following prefixes:
Parameters ( P_ )Parameters variable are used to allow data entry at the selection screen before program execution. These variables have a
limited length of eight (8) characters. Variable types of this category must be prefixed with P_. The following are
examples of variable names to be used.
PARAMETER: P_VKORG TYPE MVKE-VKORG,P_VTWEG TYPE MVKE-VTWEG.
Parameter used as checkbox ( PX_ )and (RB_)for parameter used as radio-button
Select-options ( S_ )The SELECT-OPTIONS for statement generates a program variable used for selection
criteria. This allows a user at the selection screen to enter in a range of values. The variable generated is actually a
system-generated table containing -high value, -low value, -sign, and -option
for the table field selected. Variable types of this category must be prefixed with S_ and have a limited length of eight
(8) characters. The following are examples of variable names to be used:DATA: V_MATNR TYPE MARA-MATNR.
8/8/2019 37719530 ABAP Programming Standards
8/33
SELECT-OPTIONS: S_MATNR FOR V_MATNR.
Ranges ( R_ )
The RANGES for statement generates a program variable used for selection criteria muchlike the SELECT-OPTIONS. The variable generated is actually a system-generated table containing -high
value, -low value, -sign, and -option for the table field selected. Variable types of this
category must be prefixed with R_ and have a limited length of thirty (30) characters. The following are examples of
variable names to be used:
DATA: V_MATNR TYPE MARA-MATNR.
RANGES: R_MATNR FOR V_MATNR.
Constants (C_ )
Constant variables do not change during the execution of a program. Whenever possible the literal itself should be used
These field types should be prefixed with C_. The following are examples of variable names to be used:
Example:
DATA: C_MATNR TYPE V_MATNR VALUE 000000000010000001,
C_TRUE VALUE 1,
C_FALSE VALUE 0.
Counters ( N_)A counter is a variable which is incremented once for each iteration.
Internal table (IT_) for Standard tables, (IS_) for Sorted tables, (IH_) for hash tablesTYPES TYPE|LIKE OF [WITH UNIQUE/NON-UNIQUE ]
[INITIAL SIZE ] {WITH HEADER LINE].
Types of tables:
1. Index Table - Standard Table and Sorted Table
2. Hashed table
Standard Table:
We can access records either using the table index or the key. If we use the key the response time is in linear relation to
the number of table entries. The key of a standard table is always NON-UNIQUE. Standard tables are generically index
tables.
Sorted table:
The entries are always saved and sorted according to the key. We can access records either using the table index or the
key. If we use the key, the response time is in logarithmic relation to the number of table entries since the system uses
binary search. The key of a standard table can be either UNIQUE or NON-UNIQUE. Sorted tables are generically index
tables.
Hashed table:
We can access hashed tables using their key only. The response time is constant and does not depend on the number of
the entries since the system uses a hash algorithm. The key of a standard table must always be UNIQUE.
Guidelines for using internal tables: -
We have to use WITH TABLE KEY when reading sorted and hashed tables otherwise the system may use wrong
procedure.
Do not fill sorted tables using index operations.
A sorted table cannot be resorted.
Hashed tables cannot use index operations.
Hashed table is used to store frequently read master data in an internal hashed table to avoid redundant database reads.Key access can be used with any table type.
We should never use the older techniques in the 4.X development
TYPES: BEGIN OF T_MARA,
MATNR TYPE MATNR,
MAKTX TYPE MAKTX,
WERKS TYPE WERKS_D,
8/8/2019 37719530 ABAP Programming Standards
9/33
END OF T_MARA.
DATA: IT_MARA TYPE STANDARD TABLE OF T_MARA WITH HEADER LINE.
DATA: BEGIN OF IT_INTTAB OCCURS 100,
FIELD1 LIKE SG-FIELD1,
FIELD2 LIKE SG-FIELD2,
DATA: END OF IT_INTTAB.
Dont use occurs 0 in the internal table declaration , if less than 8kb is stored in the internal table.
Use the approximate number of rows in the internal table declarationThe CLEAR should be used to initialize the table header record.
The REFRESH should be used to delete all table entries and release any paged out area. It is recommended tha
before a table is used; perform a REFRESH then a CLEAR in this order. A REFRESH does not clear the header record.
The FREE should be used at the end of the program in the wrap-up section. Performing a FREE will release
the storage area in the system roll area allotted to the table and deletes all lines.
Structure ( X_ )
Records or Structures consists of a fixed number of data objects (also called components of the record)
Example: DATA: BEGIN OF X_STRUCTURE,
FIELD1 LIKE SG-FIELD1,
FIELD2 LIKE SG-FIELD2.
FIELD1 TYPE SG-FIELD1,
FIELD2 TYPE SG-FIELD2.
INCLUDE STRUCTURE MARA.DATA: END OF X_STRUCTURE.DATA: X_MARA TYPE MARA.
Flags ( FG_ )Flags are variables that contain only one of two values. These variables will be defined as character of length 1. In allcases, the following values must be complied with:
Should be used for "NO"/ "FALSE"/"OFF"
X should be used for "YES"/"TRUE"/"ON"
These variables types are to be suffixed with FG_. The following are examples of variable names to be used:
Eg. W_EOF_FG TYPE C
W_CONTINUE_PROCESSING _FG TYPE C
Error MessagesThe purpose of this section is to define the naming conventions to be used for standard error messaging. Standard SAP
error messages should be used whenever possible to eliminate redundancy. If it is determined that additional error
messages are to be generated, assign them according to the guidelines described in this section. The following are the
three parameters to be defined in this section:
Message ID
Message SeverityMessage Number
Message IDsMessage IDs are twenty character names given to a group of related messages. The following are the naming standards
by position for message IDs:
1 "Z" Required by SAP2 Application area code (Ref. Appendix A)
2 - 20 Meaningful description
Message SeverityMessage severity defines the action performed upon execution of the message. The following are the allowable messageseverity codes:
A "Abend" - the transaction aborts and the user is unable to continue.
E "Error" - entered data is invalid. The user must modify or reenter the data.
W "Warning" - the program allows the user to override the particular warning and continue, or modify the data, which
caused the warning.
I "Information" - displays information that may be of interest to the user. The user must press enter to continue.
S "Success" - a success message is an informational message displayed on the next screen,
Such as "Transaction completed successfully".Message Number
8/8/2019 37719530 ABAP Programming Standards
10/33
Message numbers are the unique 3-character identifiers of a message. Message numbers range for 001 to 999. The next
available should be used.
SubroutinesIf a block of code is executed more than once, it should be placed in a subroutine at the bottom of the code. This makes
the code more readable, requires less indentation, and is easier to debug since the debugger can jump through an entire
subroutine via a PF key. The name of the subroutines should be descriptive and less than 30 characters.
Use local variables whenever possible within subroutines for modularization purposes. However, frequently used
subroutines within one program call should use global variables to eliminate creation time of those local variables.Prefix with L for the respective declarations.
It is recommended to pass data to and from subroutines using the USING statement in the perform. This does not apply
to field initialization subroutines and global subroutines.
Use of the CHANGING clause is up to programmer preference but is good for subroutine documentation.
Subroutines that are to be called by multiple programs should be created as a function module. External subroutines
should also be implemented as Function Modules.
Subroutine examples:
FORM CALCULATE_MATURITY_DATE.
MAT_DT = SY-DATUM + DAYS.
ENDFORM.Because of the added overhead of calling subroutines, functions, etc., you should avoid the following style of coding:
PERFORM SUB1.
FORM SUB1.
IF field NE 0.
..ENDIF.
ENDFORM.
Instead, code the following:
IF field NE 0.
PERFORM SUB1.
ENDIF.
FORM SUB1.
ENDFORM.All Subroutines (Forms) must be placed after the END-OF-SELECTION statement.
Order of forms should be the same as that of performs (not a hard and fast rule).Always have a type declaration for the formal parameters. If a particular parameter is likely to assume different types of
values use TYPE ANY.
There are several ways to assign type specifications to subroutine parameters:
FIELD2 LIKE BTABLE-FIELD2.
The type of the data object dbtable-field2 is used as the basis for type checking which then takes place as with TYPE.
FIELD3 TYPE C ... assigns to field3 the self-defined or predefined type C.
With the type specifications ANY, TABLE, C, N, P and X, typing of the formal parameter is generic.FIELD4 TYPE LINE OF ITABLE.
The type ITABLE must be an internal table. Field1 gets the line type of ITABLE. Type checking then takes place as with
TYPE. Typing of this kind is not allowed with TABLES parameters.
FIELD5 LIKE LINE OF ITABLE.
The line type of the internal table ITABLE is used as the basis for type checking which then takes place as with TYPE.Typing of this kind is not allowed with TABLES parameters.
If the actual parameter has a generic type, e.g. a generic formal parameter is passed to another typed formal parameter;complete type checking cannot be performed until runtime.
Incorrect type specifications then result in a runtime error.
Literal Text:
Literal text, which is printed on the report, should be handled in two ways.
One way is to hard code the literal in the code and give the option of maintaining Text Elements for multi-lingual clients
So, the following form of literal text should be used most of the time.
WRITE:/ 'Grand Total:'(001).
Another way is to always use Text Elements.
8/8/2019 37719530 ABAP Programming Standards
11/33
WRITE:/ TEXT-001.
The advantages to the first way are readability and the Text Element only needs to be maintained for multi-lingual
clients. The advantage to the second way is easier maintainability if TEXT-001 is coded several times in the program
and it needs to be changed.
PF-StatusPF Status is a custom status bar defined to be used by a screen or interactive program to enable user actions. The
standard SAP format must be used. The table below defines the usage of standard function keys. These function keys do
not have to be enabled but when used, must comply with the standards defined in this section. These function keys arenot to be replaced by user defined keys. The OKCODE is of length 10 characters.
PF Key OK-CODE Description
01 HELP Display help screen for current field
02 PICK Select entry (same as double-click).
03 BACK Exit current transaction. Overrides mandatory entries.
04 LIST List Possible Entries.
10 MENU Menu bar.
11 SAVE Save entries.
12 RW Cancel current request, Mandatory entries override.
13 PRI Print.14 DLT Delete.
15 EXIT Exit (Fast EXIT) leave transaction. Same as PF03.
21 P-- First page of document.
22 P- Previous page.
23 P+ Next page.24 P++ Last page of document.
External FilesExternal files are to be defined as logical files via the customization menu path. This allows for consistent naming of
files without having programs being dependent on the actual UNIX file name.For Presentation Server Upload/Download, use
GUI_UPLOAD instead of WS_UPLOAD and
GUI_DOWNLOAD instead of WS_DOWNLOAD.
VariantsVariants are program specific objects, which define, set parameter entries required at program execution time. Variant
names will consist of fourteen (14) characters formatted as follows:Position Description
1 Usage:
"Y" Tools and Utilities that are not to be migrated to production.
"Z" Application programs that will be moved to production.
2 SAP Application area (Ref. Appendix A)
4-7 FUNC for function programs
"REPT" For Report programs, interactive report programs
BDCP for BDC programs
BOLT for Bolt on ProgramsSCRP for Script driver programs
INCL" For Include Module
MODP for Module pool programs
SUBP for Subroutine pools
INTP for Interface pools
CLSP for Class pools
8 Underscore "_"
9 "V" for variant.10-14 Meaningful information
MessagesAll Error messages are to be implemented via MESSAGE IDs (Ref. Section 2.5.1). Any text messages must use
NUMBERED-TEXT, defined via include text. The purpose of this is to make any output message text language
dependent.
Report Formatting
8/8/2019 37719530 ABAP Programming Standards
12/33
Blank lines are to be specified using SKIP as opposed to multiple WRITE / statements.
Use NUMBERED-TEXT for all screen text to be displayed. This is defined via include text and is language dependent.
Batch Data InputBatch data input sessions should be limited to approx. 250 transactions per BDC group. This number can vary greatly
depending on the quality of the data being processed. Large batch ABAP programs are to be avoided due to the single-threaded nature of the batch environment. These programs are to be broken up into smaller batch programs, where
appropriate.
Authorization CheckingAuthorization objects should be checked at the selection screen of report programs or at the transaction code level. All
check objects created must be documented thoroughly and given to the security administrator.
Lock objectsLock objects should be created as function modules (Enqueue / Dequeue) in a customer function group.
DebuggingAll debugging code must be removed from a program before migration to a controlled environment (i.e. Quality
Assurance, Production). This includes breakpoints and any code associated with testing.
ABAP code is fairly self-documenting. However, it is wise to provide future programmers with documentation. Explain the
purpose, design, structure and any testing hints at the top of the program. Maintain a history of modification notes, dated,
with the most recent change first. Comment work fields, and fields in work records especially those used for interfacing.
Comment all subroutines with their purpose. Comments should explain what the code is doing, not how the code is doing it.
Do HELP EDITOR and read the documentation on the IC command.
For Report Headers: -
Refer Appendix B.
For documenting Changes within a program:-
*-------------------------------------------------------------------------------** Begin of Change as part of # Request | User Name |On
*-------------------------------------------------------------------------------*
*-------------------------------------------------------------------------------** End of Change as part of # Request | User Name *
*-------------------------------------------------------------------------------*
For declarations:-
Database Tables:-Description of the table should be documented against the table name
*----------------------------------------------------------------------*
* Declaration for Tables
*----------------------------------------------------------------------*
Global variables:-Short description of the variable should be documented against the variable name
*----------------------------------------------------------------------** Declaration for Variables
*----------------------------------------------------------------------*
Constants:-
Short description of the constant should be documented against the constant name
*----------------------------------------------------------------------*
* Declaration for Constants
*----------------------------------------------------------------------*
Flags:-
8/8/2019 37719530 ABAP Programming Standards
13/33
Short description of the flag should be documented against the flag name
*----------------------------------------------------------------------*
* Declaration for Flags
*----------------------------------------------------------------------*
Internal tables:-
Short description for the use of internal should be documented against the internal table name*----------------------------------------------------------------------*
* Declaration for Internal tables
*----------------------------------------------------------------------*
Events:-
Should be of the type given below
Start of Selection:-
*----------------------------------------------------------------------** Start of Selection
*----------------------------------------------------------------------*
Subroutines:-
*&---------------------------------------------------------------------*
*& Form test_ for_ material_ type
*&---------------------------------------------------------------------*
* Description
*----------------------------------------------------------------------** --> Formal parameter type and description*----------------------------------------------------------------------*
Avoid Dead Code:Avoid leaving "dead code" in the program. Remove defined fields, which are never referenced, and code, which can
never be logically executed. Always perform Extended Program Check (EPC) before delivering the object. The path for
EPC is ABAP editor -> Program -> Check -> Extended Program Check.
Logical Database:Choose the most efficient logical database possible. Study the selection criteria and which secondary indexes are used
for that view. Provide the appropriate selection criteria to limit the number of database read. Force users to provide
selection criteria by evaluating the selection criteria entered on the selection screen during the AT SELECTIONSCREEN event. Remember the power of match codes / Search Helpsfor selection and report sorting. Always use GET
statement to retrieve the required fields.
Use the new features as of release 4.x as mentioned below:-
Basic form NODES node.
Additions:1.... TYPE type.
There are four different types of nodes in a logical database:
(Refer to help on LDB for further details)
Use LDB_PROCESS function module as of release 4.6 to call LDBs without having to change roll areas. (Refer to
Function module documentation on LDB_PROCESS for further details)
Adjustment to the Function Builder: The program structure created and the logical database builder have both been
modified to forms recognized by the function builder.
Techniques for efficient Database selectionThe following basic guidelines need to be considered while retrieving data from the database:
Avoid unnecessary database accesses
Keep the number of data records small
Reduce information transfer to application server
Reduce the load on the database engine
Use database locks and SAP Enqueue
8/8/2019 37719530 ABAP Programming Standards
14/33
A detailed explanation for each of these rules is as under.
Reduce Information transfer to Application server.
Specify the individual column (field) names of the data you want to retrieve in the select statement
E.g. SELECT single MATNR ERSDA
INTO (V_MATNR, V_ERSDA)
FROM MARAWHERE MATNR EQ 000101234567890123.
In this example, only 2 fields are transported back to the work area for each matching record. This greatly reduces the
amount of data transfer (network traffic) - especially for tables, which have a large number of fields/large record size.
Our objective is to reduce network traffic as much as possible and for this reason, ABAP provides several Aggregate
functions, which are part of the SELECT, statement. By using these, the DBMS makes the computations instead of
transferring all the data to the application.
e.g.1 Use: SELECT COUNT(*)FROM MARC
WHERE MATNR EQ 000101234567890123.
SY-DBCNT will hold the number of matching records found.
Instead of: SELECT * FROM MARC
WHERE MATNR EQ 000101234567890123.
ADD 1 TO V_COUNT.
ENDSELECT.
e.g.2 Use: SELECT SUM( TRAME )
INTO V_TOTAL_IN_TRANS
FROM MARC
WHERE MATNR EQ 000101234567890123.
Instead of: SELECT * FROM MARC
WHERE MATNR EQ 000101234567890123.V_TOTAL_IN_TRANS = V_TOTAL_IN_TRANS + MARC-TRAME.
ENDSELECT.
Use update statement sparingly. Only update the columns, which are changed, and do not overwrite the entire line
While using SELECT SINGLE
SELECT SINGLE is used instead of SELECT-ENDSELECT loop if full primary key is known. Otherwise, use
SELECTup to 1 Rows. SELECT SINGLE requires one communication with the database system.
Ex. Use SELECT SINGLE * FROM SCARR WHERE CARRID = 'LH'.
Instead of SELECT * FROM SCARR
WHERE CARRID = 'LH'.
ENDSELECT.
Keep the number of data records small.
Never use Nested SELECT loops. Instead consider options: Views, Joins or select statement with for ALL ENTRIES
OPTION
Always use the WHERE clause in the corresponding SQL statement. An Application should read only those lines o
the table that are necessary for the processing. Therefore formulate filter condition not through CHECK statements
rather through part of WHERE statements
E.g. Always use option 1 instead of option 2.
Option 1
E.g. SELECT MATNR
8/8/2019 37719530 ABAP Programming Standards
15/33
INTO TABLE IT_MARA
FROM MARA
WHERE MATNR LIKE 23%.
Option 2
E.g. SELECT MATNR
INTO MARA-MATNRFROM MARA.
CHECK MARA-MATNR+0(2) NE 23.
MOVE MARA-MATNR TO IT_MARA-MATNR.
APPEND IT_MARA.
CLEAR IT_MARA.
ENDSELECT.
Use the indexes of the relevant database tables to make your WHERE clause more efficient, by checking all index fields
for equality (EQ, =) and using the AND operator. The primary key of a database table is automatically its primary index
You can also create secondary indexes for a database table in the ABAP Dictionary. However, certain considerations
need to be made while creating secondary indexes.
The success with which an index supports data selection from a table is dependent on how closely the dataset selected
using the index represents the dataset finally to be selected. This can be best illustrated by means of an example.
An index to the table EXTAB containing the fields FIELD1, FIELD2, FIELD3 and FIELD4 in this sequence is to be
defined. The table is to be accessed using the SELECT statement:
SELECT *
FROM BSPTAB
WHERE FIELD1 = X1 AND
FIELD2 = X2 AND
FIELD4 = X4
Since FIELD3 is not specified more precisely, sorting of the index functions only up to FIELD2. If the database system
accesses the data using this index, it will quickly be able to access all records for which FIELD1 = X1 and FIELD2 = X2
are valid. It will then have to select all the records for which FIELD4 = X4 from this set.
Some Guidelines while creating Indexes
The speed of access provided by this index is heavily dependent on how closely the dataset selected via the indexcorresponds to the dataset to be finally selected.
Consequently, the sequence of the fields in the index is decisive in determining the speed with which data records are
accessed.
Fields, which frequently contains constants in many selections, should be located at the beginning. An index assistsselection only up until the first unspecified field. Fields should be included in an index only if they significantly restric
the set of data selected.
E.g.: The following selection is often made from an address file ADRTAB:
SELECT * FROM ADRTAB WHERE TITLE = 'Prof.' AND NAME = X AND FIRSTNAME = Y In an index
containing the fields NAME, FIRSTNAME and TITLE, the field TITLE would rarely narrow down further the records
specified via name and first name. It would not be useful, therefore, to include this field in such an index. An index
containing only the field TITLE might be useful, for example, if it is often necessary to select all the professors.
If selections are frequently made involving attributes that are not contained in the primary index, you should define
secondary indexes.
Please note that any additional indexes you create may place an additional load on the system, since they have to be
adjusted each time a change is made to the table contents. Every additional index therefore slows down the insertion of
records in the table. Tables in which entries are frequently written should generally therefore have only a few indexes.
Even if a suitable index exists for a selection, it may not always be used. The index selected depends on the database
system optimizer in use. You should usually therefore check whether an index is in use (see How do you check whether
an index is used? ).
8/8/2019 37719530 ABAP Programming Standards
16/33
The indexes for a table should therefore be as distinct as possible - that is, they should have as few fields in common as
possible. If two indexes for a table have many fields in common, this can complicate the choice of the most selective
index by the optimizer.
Define a database view via the ABAP Dictionary, which identifies the tables and fields that you are interested in. Then
SELECT from the view rather than the database table(s).
E.g. SELECT *
FROM Z_M_MARCWHERE MATNR EQ 000101234567890123.
This is preferable if multiple programs require the same data from the same table(s). If the set of data in these programs
requires changes, then the developer need only change the definition of the database view, rather than modify every
SELECT statement - i.e. greater reusability and maintainability.
If possible, avoid using the NOT operator in the WHERE clause, because it is not supported by database indexes; Inver
the logical expression instead.
Avoid using complex WHERE clauses since the system has to break them down into several individual statements for
the database system
If all you are interested in is retrieving all possible values for a given table field (i.e. you do not want duplicates), then
SELECT DISTINCT will provide that capability and will also restrict the amount of data passed back to the application
to only the set of unique values.
E.g. SELECT DISTINCT WERKS INTO V_PLANT FROM MARC.
ENDSELECT.
In this example, a value will be returned for each unique value of the field WERKS (Plant). If there are 3 unique plants
in table MARC, will be performed 3 times only, with each value of WERKS being placed into the work
area V_PLANT for each iteration. Each plant may, in reality, be present on multiple records, but this method returns
only unique values.
Be careful while restricting data on NULL values.
You will not find a record in a database table, if field has a Null Value and you are using the
Following WHERE-clauses:WHERE FIELDN = 0.
WHERE NOT fieldn = 0.
WHERE fieldn < 5.
WHERE fieldn > 5.
WHERE fieldn = SPACE.
WHERE fieldn SPACE.
If you want to read records with Null Values, you have to use IS NULL with your WHERE-clause:WHERE fieldn = 0 OR fieldn IS NULL.
WHERE fieldn < 5 OR fieldn IS NULL.
WHERE fieldn = SPACE OR fieldn IS NULL.
Where possible, avoid accessing the same data more than once (for example, by using SELECT before an UPDATE or
DELETE statement).
Reduce the load on the database engine
Use the 'into' syntax and push data directly into internal tables rather than using the row by row 'append' approach
Again this is an example of thinking in terms of 'sets' rather than 'rows'. Old-fashioned databases only knew about rows
Modern relational databases work better when dealing with sets of data. Try to work always in sets.
The order of the fields in the where clause of the select must be in the same order as the order in the Index. (Oracle
limitation but routinely should be used against all databases).
The addition INTO CORRESPONDING FIELDS in the INTO clause of the SELECT Statement is only effective for
large amounts of data, because the time required to compare the field names is otherwise too great.
8/8/2019 37719530 ABAP Programming Standards
17/33
There are two ways to get ordered data. The data can be selected using the addition ORDER BY from the database. Thi
is advisable for large amounts of data (> 10 MB) because the database system is the only component in R/3 with large
resources. Ensure that the ORDER BY can use an index. When a small amount of data is to be sorted, it can be done
with ABAP statement SORT.
Exactly the same is also valid for the usage of DISTINCT vs. DELETE ADJACENT.
Avoid unnecessary database accesses
Dont use identical select statements.
Use option 1 instead of option 2.
Option 1
e.g. To get Material DescriptionsLOOP AT IT_VBAP.
READ TABLE IT_MAKT KEY MATNR = IT_VBAP-MATNR TRANSPORTING MAKTXIF SY-SUBRC NE 0.
SELECT MATNR MAKTX APPENDING TABLE IT_MAKT-MAKTX WHERE MATNR
EQ IT_VBAP-MATNR.
ENDIF.
MOVE: IT_MAKT-MAKTX TO IT_VBAP-MAKTX.
ENDLOOP.
Option 2e.g. To get Material Descriptions
LOOP AT IT_VBAP.
SELECT SINGLE MAKTX INTO IT_VBAP-MAKTX WHERE MATNR EQ IT_VBAP-MATNR.
ENDLOOP.
Using Database Buffering
Saving database tables in local buffers can save a considerable amount of time. Wherever possible, use buffered data
and only use the BYPASSING BUFFER addition where absolutely necessary.
Note that the following additions automatically bypass the buffer:
SELECT ... BYPASSING BUFFERAny SELECT from a view (except a projection view)
SELECT FOR UPDATE...
Any aggregate function (COUNT, MIN, MAX, SUM, AVG)
Example: SELECT MIN (field1) FROM dbtable1 WHERE...
SELECT DISTINCT...
WHERE-clause contains ... IS (NOT) NULL
ORDER BY (other than PRIMARY KEY)
Any Native SQL statement
Joins.
An INNER join is a join where you expect that there will always be a relationship between all of the tables in the set, andif any of the relationships are missing, then you do not want to get the row.
Eg.
Consider 3 imaginary tables.Customer
MANDT (Primary Key)
CUST_CODE. (Primary Key)
Invoice
MANDT (Primary key)
INV_NUM (Primary key)
CUST_CODE (Foreign key to Customer)
Invoice_line
8/8/2019 37719530 ABAP Programming Standards
18/33
MANDT (PK)
INV_NUM (PK)
INV_LINE_NUM (PK)
You could construct an INNER join over these tables as follows
Customer Invoice Invoice_line
MANDT MANDT MANDT
inv_num === inv_numcust_code === cust_code
Say you then have to report off this information.
Your report would contain ONLY those customers which had Invoices which had at least one line. Customers without
invoices would not be included. Customers that had invoices but without a line would not be included.
This is the principle of the INNER join. All the data has to be there and be related.
Database views support ONLY the inner join concept.
Outer Joins
In the majority of cases inner joins will actually be the requirement, but in the minority of cases you will want to use an
outer join. Outer joins are useful where you may need all records from a certain table, that meet the selection criteria, and
all data from another table(s), IF it exists. But if the latter data does not exist, you still want to get the first table data.
Using our imaginary tables again.Suppose the requirement is not for an invoice report, but for a customer report, showing outstanding invoices. You want
to see ALL customers, so you can't use an inner join
(Incidentally therefore you can't use a database view, database views only support INNER joins) because if you did, you
would not see customers that had no invoices. So you would construct an outer join relationship as under:
Customer Invoice Invoice_line
MANDT MANDT MANDT
inv_num === inv_numcust_code ----> cust_code
In this situation you would get all customers regardless, and their invoices. You would only see the invoices, which had
at least one line as the join between invoice and invoice_line is still an inner join. If you wanted to be absolutely sure you
could code a double outer join as under:
Customer Invoice Invoice_line
MANDT MANDT MANDT
inv_num ----> inv_num
cust_code ----> cust_code
In this situation you would see all the invoices, even if they had no lines.
In reality in the above situation you would seldom code such a well defined relationship as invoice - invoice_line using
an outer join. If an invoice doesn't have a line then it is usually corrupt data.
Guidelines for using Joins
Using outer joins places a heavy load on the database engine (although no heavier that if you coded a nested select), so
be very parsimonious about the use of outer joins.
The performance of the join depends on the database optimizer used especially if there are more than two tables used for
joins.
Try to give maximum number of conditions in the ON clause. This is because the ON conditions are evaluated first and
the virtual table created as a result is the one on which the WHERE clause applies.
To process a join, use a view wherever possible instead of nested SELECT statements.
Using nested selects is a technique with low performance. The inner select statement is executed several times, which
8/8/2019 37719530 ABAP Programming Standards
19/33
might be an overhead. In addition, fewer data must be transferred if another technique would be used eg. Join
implemented as a view in ABAP Repository.
Use sub queries if possible. However, be careful while choosing the type of sub query to be written.
Example
Selects the flights for which at least one booking exists:
TABLES SFLIGHT.
SELECT * FROM SFLIGHT AS FWHERE EXIST
( SELECT * FROM SBOOK
WHERE CARRID = F~CARRID
AND CONNID = F~CONNID
AND FLDATE = F~FLDATE ) .
WRITE: / SFLIGHT-CARRID, SFLIGHT-CONNID, SFLIGHT-FLDATE.
ENDSELECT.
This is most assuredly not a Good Thing. What this is actually doing is forcing the database to do a separate selection
from SBOOK for each row in SFLIGHT. For a small number of records this would probably work OK - but once again
- on larger datasets it would hang. For every record in SFLIGHT a separate database operation is occurring in SBOOK
You might as well have coded the selections inside a loop.
This query is better written as follows;Select distinct F~*
into table IT_SFLIGHT
From SFLIGHT as F
INNER JOIN SBOOK as s on
S~CARRID = F~CARRID AND
S~CONNID = F~CONNID AND
S~FLDATE = F~FLDATE.
Following the above guidelines does not guarantee the most optimal selection from the database. Ultimately, it dependson the nature of the data and other associated factors.
Hence, it becomes mandatory to analyze the Selection from the database with the help of SQL Trace Tool. The following
features need to be checked in ST05:
a. Explain SQL.b. Identical select
c. Check summary
SQL Tuning Checklist
Consolidated selections
No row by row processing
No check statements
No selections within loops
Selections are 'into' internal tables - no appends
SQL trace check completedAll programs checked to make sure that they are using the full index and in the
Correct order.
Minimum or zero number of identical selects.
Use of appropriate Indexes
Internal TablesThe following are the guidelines for working with the Internal Tables:
Always use the READ statement with the Index or BINARY SEARCH.
Always read the required fields using TRANSPORTING f1 f2
Avoid nested looping on the internal tables.
Use EXIT statement to jump out of the loop, when the complete processing is done.
8/8/2019 37719530 ABAP Programming Standards
20/33
As far as possible avoid using Modify, Insert, Update, Append or Delete within the loop endloop.
For e.g.
Looping at ITAB:
INSERT INTO dbtable VALUES itable. NOT Preferred
ENDLOOP.
INSERT dbtable FROM TABLE itable
ACCEPTING DUPLICATE KEYS.IF NOT SY-SUBRC IS INITIAL.
... error handling
ENDIF.
When multiple records are to be inserted into a table, then use the second form as shown above rather than loop into the
internal table and inserting/updating single records.
INITIAL SIZE
This size does not belong to the data type of the internal table, and does not affect the type check. You can use the above
addition to reserve memory space for table lines when you declare the table object.
When this initial area is full, the system makes twice as much extra space available up to a limit of 8KB. Further memoryareas of 12KB each are then allocated.
You can usually leave it to the system to work out the initial memory requirement. The first time you fill the table, little
memory is used. The space occupied, depending on the line width, is 16
8/8/2019 37719530 ABAP Programming Standards
21/33
There are less than 100 rows
Rows are already in sorted order
If an internal table must be sorted and the above cannot be satisfied, fill the table in unsorted order and then sort
specifying key fields. To remove duplicates, if required, collect the rows from the sorted table into an auxiliary table.
Use APPEND LINES OF [FROM ] [TO ] TO
When appending fixed lines from an internal table to a new internal table.
MOVEAvoid unnecessary Moves by using the explicit work area operations:
APPEND workarea TO itable
INSERT workarea INTO itable
COLLECT workarea INTO itable
MODIFY itable FROM workarea
READ TABLE itable INTO workarea
LOOP AT itable INTO workarea
Move Command:When records a and b have the exact same structure, it is more efficient to MOVE a TO b than to MOVE
CORRESPONDING a TO b, if records a and b have the exact same structure.
MOVE BSEG TO *BSEG. is better thanMOVE-CORRESPONDING BSEG TO *BSEG.
Note: avoid unnecessary MOVEs by using explicit work area operations.
DELETE
Where appropriate.
With the new DELETE variant DELETE itable [FROM ...] [TO ...] WHERE ... the task of deleting a set of lines can be
transferred to the kernel.
If possible, WHERE should be used together with FROM... and/or TO... to enhance performance.
The performance gain when using
DELETE itable WHERE....
instead of
LOOP AT table WHERE ...
DELETE itable.
ENDLOOP.increases with the number of entries the internal table contains and the number of lines to be deleted.
When deleting adjacent duplicates use COMPARING fields as far as possible.
e.g. DELETE ADJACENT DUPLICATE ENTRIES from COMPARING F1 F2 If Condition:
When coding IF tests, nest the testing conditions so that the outer conditions are those, which are most frequently true
This will ensure minimal code execution. Similarly, for logical expressions with AND, place the most likely false firsand for the OR, place the most likely true first.
Case Statement:When testing fields "equal to" something, one can use either the nested IF or the CASE statement. The CASE is bette
for two reasons. It is easier to read and after about five nested IFs the performance of the CASE is more efficient.Note: CASE statement used in place of IF where field checked for > 2 values.
ABAP StatementsThe following should be avoided in the ABAP statements to improve efficiency:
Type conversions: The processor takes additional time to convert from one data type to another.
Type P fields: Unless rounding errors are not avoidable, do not use packed data variables.Nested Loops: Unless unavoidable, do not use nested loops. They eat up processor time.
If nested loops are unavoidable then
Avoid the following
8/8/2019 37719530 ABAP Programming Standards
22/33
SORT: I_VBAK by VBELN, I_VBAP by VBELN.
Loop at I_VBAK
Loop at I_VBAP where VBELN = I_VBAK-VBELN.
.
Endloop.
Endloop..
Instead use
SORT: I_VBAK by VBELN, I_VBAP by VBELN.
Loop at I_VBAK
Read table I_VBAK with key VBELN = I_VBAK-VBELN binary search transporting no fields.
Loop at I_VBAP from sy-tabix.
If I_VBAP-VBELN I_VBAK-VBELN.
Exit.Endif.
Endloop.Endloop.
Describe Statement:DESCRIBE TABLE [LINES ] [OCCURS ] [KIND ]To find out how many entries are in an internal table use DESCRIBE.
DESCRIBE TABLE ITAB LINES CNTLNS. is more efficient than
LOOP AT ITAB.CNTLNS = CNTLNS + 1.
ENDLOOP.
Field Length:To find out the length of a field use the string length function.
FLDLEN = STRLEN (FLD). is more efficient than
IF FLD CP * #.
ENDIF.
FLDLEN = SY-FDPOS.
Arithmetic OperatorsUse symbols for arithmetic operators instead of characters for better performance.Example: use instead of NE .
Use of tablesInternal tables vs field groups:
Using internal tables is more efficient than field groups and should be used when possible.
If the volume of data is very much, field groups are more efficient compared to internal tables in terms of memory
management.
WHERE clauseAlways try to use the columns which are used in indexes in SELECT statements WHERE clause along with other non-
indexed columns in the WHERE clause.
Aggregate functionsUse of aggregate functions in the SELECT expression list to find the minimum, maximum, count and average list instead
of computing it yourself.
JoinTo process a join, i.e. process data from 2 or more tables use view instead of nested select statements.
Not OperatorThe NOT operator cannot be used in an indexed access. Still it could be specified to avoid unproductive data transfer
between the database and the application.
8/8/2019 37719530 ABAP Programming Standards
23/33
Minimizing the database loadDo not use a SELECT statement to confirm existence before UPDATE or DELETE is used. Directly use UPDATE or
DELETE and then check the result with SY-SUBRC.
When large amounts of ordered data is to be read from the database, use the ORDER BY clause. (If the index exists, le
the statement use it.) If only a small amount of data is to be needed, then use the ABAP SORT.
The same logic applies to DISTINCT and DELETE ADJACENT.
Logical databases should be used whenever available for reports.
Standards for Specific StatementsASSIGN
Use of field symbols is discouraged unless necessity dictates. Field symbols, when used, should be documented in
program comments when defined and whenever used. Always have a type declaration for field symbols.
AT PFnnUse the AT USER COMMAND instead of AT Pfnn. This ensures proper response to the user command and is more
legible.CHECK
Use check statements whenever possible instead of nested IFs.User Interface (GUI)
GUI statuses should be used for interactive report programs and online programs. Use menu bar linking whenever
possible to build consistent GUI statuses for screens within a module pool.
CHECK, EXIT, REJECT, STOP & CONTINUE
Use these statements to suspend processing and/or skip remaining unnecessary processing for improved performance.
Coding TipsA program should test the system return code field (SY-SUBRC) after any statements that could potentially change its
value unless the outcome of the statement is not important for subsequent processing. The return code should always be
checked after any database table read/update statements.
LOOP . WHERE is faster than LOOP/CHECK because LOOP . WHERE evaluates the
specific condition internally.Ex. Use
LOOP AT ITAB WHERE NAME1 = KVAL..ENDLOOP.
Instead ofLOOP AT ITAB.
CHECK ITAB-NAME1 = KVAL.ENDLOOP.
ABAP Module Pool Standards and PracticesThe purpose of this section is to define the basic standards that all developed programs must comply with when creating
or maintaining Module Pools in the SAP environment. This section describes the rules surrounding the use of ABAPfeatures and components specific to Module Pool program types. Coding in the main program must comply with
standards and practices defined for ABAP (Section 4.0).Program Structure
The ABAP Programmers Workbench (SE80) should be used to create and maintain all Module Pool programs. A sample
flow-logic and associated modules for all screens in a module pool is defined in Appendix D.Screen Definitions
Screens are to use data dictionary fields for all variables. This does not include multiple selections like radio buttons.
Screens are to be numbered with an entry screen of 100. Reuse screens whenever possible.Tab Strips:
Use Tab strips wherever possible as they provide an easy way to define different application components on the same
screen and switch between them. Their intuitive design also makes them easier for the end users.GUI interfaces
GUI interfaces must follow SAP standards. User defined menus are to contain all actions that are applicable to the
transaction. Items that are not effective during a screen process are to be disabled. Commonly used selections are toappear as push buttons below the menu bar.
POP-UP windowsPop-up windows are allowed and to be used at programmer or customer preference. Programmatic circumvention of
pop-up windows must be included for batch data processing considerations.OK_CODE (SY-UCOMM)
An OK_CODE variable must be specified in all screens. This variable is defined via the field list of each screen created
8/8/2019 37719530 ABAP Programming Standards
24/33
(Exists as the last field in the field l).Update
Never use single-line Updates.
When the fields selected are part of the key, then to avoid multiple selections, use DISTINCT clause:
This clause should be used when there is a large amount of data, which cannot be handled in the memory, and when
there is an Index.
When the data is small and there is no Index, then use DELETE ADJACENT DUPLICATES.
A Null Value is an undefined value of a field in a database table.
Outputs a Null Value:After an ADD FIELD field n in the database table. All existing entries get a Null Value for field n.
After INSERT with a database view for the fields which are not defined in the view.
When reading a field with a Null Value from the database, the result will be:
SPACE for fields with type CHAR, RAW, LANG
0 for fields with type INT4, FLTP, DECEXESThe use of indexes for the database access can vastly improve the performance of reports.
Secondary index should be created when:
you select with fields without index support
you select only a small part of the table (< 5 %)
your WHERE-clause is easy (uses only ANDs) you often have to do sorts without index support
ABAP dictionary allows 16 secondary indexes for each table. But be very careful. Inserting and
Updating records will take longer and gives the database optimizer more choices to cause faults.
Secondary Indexes
Rules to follow when creating secondary index:
An index must be selective. An index is worthless, if you still get thousands of records.
Dont use too many fields. Most database systems use only a certain number of index
fields.
Use the most selective fields first.
Create the index for the main case. Be aware that other SELECTs can cause problems.
R/3 buffers are local to the application server and hold primarily run-time data.
Buffer types:
Table buffers for resident, generic and partially buffered tablesNumber range buffer
PXA Program buffer for ABAP loads
Presentation buffer for dynpros
CUA buffer for menu objects
Nametag buffer for ABAP dictionary information (table structures)
There are three basic buffering types:
Resident buffering (100%): the contents of the whole table are loaded into the buffer on the first access to any data from
the table.
Generic buffering a generic key (first n key fields) is specified when maintaining the technical settings. This generic key
divides the contents of the table into so-called generic areas. When accessing any data with a specified generic key, the
whole generic area is loaded into the buffer. The figure shows the case of generic buffering with one and two fields asgeneric key. A typical case of generic buffering is the client-dependent buffering (client is the first key field). When
specifying resident buffering for a client-dependent table, the ABAP Dictionary automatically uses generic buffering
with one key field.
Partial buffering (single record): only single records are read from database and stored into the buffer.
SQL statements bypassing bufferAll buffer types:
SELECT ... BYPASSING BUFFER
Any SELECT from a view (except a projection view)SELECT FOR UPDATE...
Any aggregate function (COUNT, MIN, MAX, SUM, AVG)
8/8/2019 37719530 ABAP Programming Standards
25/33
Example: SELECT MIN (field1) FROM dbtable1 WHERE ...
SELECT DISTINCT...
WHERE-clause contains ... IS (NOT) NULL
ORDER BY (other than PRIMARY KEY)
Any Native SQL statement
There are several statements, which cannot be satisfied from the buffer. These statements bypass the buffer and are sent
directly to the database. The above shows the statements that bypass any buffer type.
These statements should be avoided when programming with buffered tables in order to guarantee good performance. Anexception is the maintenance transactions on buffered tables.
These should use an explicit SELECT... BYPASSING BUFFER to ensure the most-up-to-date data directly from the
database.
R/3 Buffers - Possible Usage:
A productive system rarely changing data:
Table buffers for tables with:
Rather small size
('small' depends on access frequency)
Read-mostly access
E.g. control tables, customizing tables,
'small' master data
Special buffer for runtime objects: programs, dynpros, table structures
Buffering can be done only if there are no indexes:
A full table scan in buffer can be worse than a select with index from the database
ABAP Objects is a new concept in R/3 Release 4.0. The term has two meanings. On the one hand, it stands for the entireABAP runtime environment. On the other hand, it represents the object-oriented extension of the ABAP language.
This documentation introduces a selection of terms that are used universally in object orientation and also occur in
ABAP Objects.
Classes
Classes consist of ABAP source code, enclosed in the ABAP statements CLASS... ENDCLASS. For a local class, youenter this source code directly in the corresponding ABAP program. For a global class, it is generated by the Class
Builder in special tables within the R/3 Repository.
A complete class definition consists of a declaration part and, if required, an implementation part. The declaration part of
a class is a statement block:
CLASSDEFINITION.
...
ENDCLASS.
It contains the declaration for all class components (attributes, methods, events). When you define local classes, the
declaration part belongs to the global program data. You should therefore place it at the beginning of the program.If you declare methods in the declaration part of a class, you must also write an implementation part for it. This consist
of a further statement block:
CLASS IMPLEMENTATION.
...
ENDCLASS.
You can divide the declaration part of a class into up to three visibility areas:
CLASS DEFINITION.
PUBLIC SECTION.
...
8/8/2019 37719530 ABAP Programming Standards
26/33
PROTECTED SECTION.
...
PRIVATE SECTION....
ENDCLASS.
(For further details refer help on defining classes.)
CLASS-DATA ( a).
Declares static attributes in a class or an interface in ABAP Objects.
CLASS-METHODS meth.
CLASS-METHODS meth FOR EVENT evt OF cif.
Declares static methods in a class or interface in ABAP Objects.CLASS-EVENTS evt.
Declares static events in a class or interface in ABAP Objects.CLASS-POOL.
Additions:1. ... MESSAGE-ID mid
Introductory statement for a class pool. Class pools are programs with type Class Pool that serve as containers for globa
classes. You cannot enter the CLASS-POOL statement in a program yourself. Instead, it is generated by the Class
Builder.
Reference Variables
Objects are runtime instances of classes in the memory area of a program. A program accesses individual objects usingpointers called reference variables.
You declare reference variables using the statement
DATA TYPE REF TO .
Object Instances
Once you have declared an object variable for a class , you can create an object using the statement
CREATE OBJECT .To access the object components using the object variable , use the following syntax:
To access an object attribute : < obj>->To call a method : CALL METHOD < obj>->
Defining Interfaces
You can define interfaces in a similar way to classes; either locally in your program, or globally using the Class Builder
The definition of an interface consists only of a declaration part:
INTERFACE ....ENDINTERFACE.Incorrect syntax in ABAP Objects
(for details refer to help on Changes in release 4.6 - ABAP Objects - Replacement of Obsolete Statements for 4.6 )
BIT - Operations:-
The bit expression bitexp is calculated and the result placed in field x.You can use the four bit operators BIT-NOT, BIT-AND, BIT-XOR and BIT-OR. The operands are linked according to
the table below.
The priority is normal: BIT-NOT has priority over BIT-AND, followed by BIT-XOR, and then BIT-OR. You can use
any number of parentheses.
x y BIT-NOT x x BIT-AND y x BIT-XOR y x BIT-OR y
0 0 1 0 0 0
0 1 1 0 1 1
1 0 0 0 1 1
1 1 0 1 0 1
8/8/2019 37719530 ABAP Programming Standards
27/33
CATCH
Variants:
1. CATCH SYSTEM-EXCEPTIONS except1 = rc1 ... exceptn = rcn.
You can catch ABAP runtime errors in the processing blockenclosed in the CATCH ... ENDCATCH statements.
Note the following:
- rc1 ... rcn must be numeric literals.- CATCH ... ENDCATCH may be placed anywhere where
IF ... ENDIF (for example) may occur. It is local, not
cross-event.
- It may be nested to any depth.
- It only catches runtime errors in the current call level.This means, for example, that runtime errors resulting from
PERFORM- or CALL FUNCTION statements are not trapped by
CATCH ... ENDCATCH.
(for the list of standard runtime catchable errors refer to help)
COMMUNICATION:-
COMMUNICATION INIT DESTINATION dest ID id.
COMMUNICATION ALLOCATE ID id.
COMMUNICATION ACCEPT ID id.
COMMUNICATION SEND ID id BUFFER f.
COMMUNICATION RECEIVE ID id
...BUFFER f
...DATAINFO d
...STATUSINFO s.6. COMMUNICATION DEALLOCATE ID id.
The COMMUNICATION statement allows you to develop applications which perform direct program-to-program
communication. The basis for this is CPI-C (Common Programming Interface - Coummunication), defined by IBM
within the context of SAA standards as a standardized communications interface.
The COMMUNICATION statement provides the essential parameters for implementing simple communication. The
basis for this is the CPI-C starter set that covers the following functionality:
Establishing a connectionAccepting a communication
Sending data
Receiving data
Closing a connection
ABAP Tabstrip Control
Basic form CONTROLS ctrl TYPE TABSTRIP.
Effect Creates a control ctrl with type TABSTRIP.
1. PUT node.
2. PUT .
You can only use this statement in the database access program of a logical database whose structure contains the node
node. You use it to pass data read by the logical database to itsuser. This is either an executable (type 1) program with the logical database entered in its program attributes, or a
program that is using the function module LDB_PROCESS. In the first case (executable programs), the "PUT node." orPUT ." statement triggers the "GET node." event in the program. In the second case, the corresponding callback
routine is called, and the data from the work area node or is passed back to it.
8/8/2019 37719530 ABAP Programming Standards
28/33
STRING and XSTRING
The elementary data type STRING is similar to data type C and refers to a variable-length string. Accordingly, the
elementary data type XSTRING is similar to data type X and refers to a variable-length byte sequence.
Area Code DescriptionF FI - Financial Accounting
D DASS (Control Station)
A AM - Assets Management
K CO - Controlling
M MM - Materials Management
V SD - Sales and Distribution
C PP - Production Planning
I PM - Plant MaintenanceQ QM - Quality Management
P PS - Project SystemU Enterprise Data Model
G General Ledger (G/L)
S Basis
Y System
E EDI
X Cross Application
1 Environment Health & SafetyN HospitalR Human Resources
H Human Resources Planning
9 Industry Solution
L Inventory Management
W Merchandise Management System
J Publishing Work Flow
************************************************************************
* Program name: Program name - Program title
*
* Description: Description of program*
* Date/Author: Date Written/Authors name
*
* Table Updates: Listing of tables updated*
* Input Parameters: (For Includes/ Function Modules)*
* Output Parameters: (For Includes/Function Modules)
*
* Return Codes:
*
* Special Logic:
** Includes:************************************************************************
* M O D I F I C A T I O N L O G
************************************************************************
* Date Programmer Request # Description
* ------ -------------- ------------- ---------------------------*
* dd/mm/yy xxxxxxxxxxxxxx nnnnn New Program
*
************************************************************************REPORT YUPSTDS .
************************************************************************
* T A B L E S
8/8/2019 37719530 ABAP Programming Standards
29/33
************************************************************************
TABLES:
************************************************************************
* S E L E C T O P T I O N S
************************************************************************
SELECT-OPTIONS:
************************************************************************* P A R A M E T E R S
************************************************************************
PARAMETERS:
************************************************************************
* D A T A
************************************************************************
DATA:
** Accumulators **** Constants **
** Switches **** Work fields **
** Internal Tables **
** Data structures / Strings **
************************************************************************
* I N I T I A L I Z A T I O N
************************************************************************
INITIALIZATION.************************************************************************* A T S E L E C T I O N S C R E E N
************************************************************************
AT SELECTION-SCREEN.
************************************************************************
* T O P O F P A G E
************************************************************************
TOP-OF-PAGE.
************************************************************************* E N D O F P A G E
************************************************************************
END-OF-PAGE.
************************************************************************* S T A R T O F S E L E C T I O N
************************************************************************
START-OF-SELECTION.
************************************************************************* E N D O F S E L E C T I O N
************************************************************************END-OF-SELECTION.
************************************************************************
* F O R M S
8/8/2019 37719530 ABAP Programming Standards
30/33
To be determined by the clients business rules.
Short Name Med. Name Long Name Description
MAT MATRL MATERIAL Material
Flow Logic
*-------------------------------------------------------------------Process Before Output.
*
module SET_STATUS . " Called by all screens
* Enter screen specific modules here i.e. dynamic screen locking, etc.
*
*-------------------------------------------------------------------
Process After Input.
* Process fast-exit commandsmodule PAI_EXIT AT EXIT-COMMAND. " Called by all screens
* Save OK_CODE pressedmodule PAI_INITIALIZE. " Called by all screens
*
* Enter screen specific modules here i.e. Field checks, Loops, Table Controls etc.
*
* Process user command ( OK_CODE ) after all checks completed
module USER_COMMANDS.
Process Before Output Modules*-------------------------------------------------------------------***INCLUDE MZxxxO01 .
*-------------------------------------------------------------------
*&---------------------------------------------------------------------*
*& Module SET_STATUS OUTPUT
*&---------------------------------------------------------------------*
* text *
*----------------------------------------------------------------------*
MODULE SET_STATUS OUTPUT.CASE SY-DYNNR. " Interrogate screen number
WHEN '0100'. " Screen description for screen 100
SET PF-STATUS '100MAIN'.
SET TITLEBAR '100'.WHEN '0200'. " Screen description for screen 200
SET PF-STATUS '200MAIN'.
SET TITLEBAR '200'.
* Add any subsequent screensENDCASE.
ENDMODULE. " SET_STATUS OUTPUTProcess After Input Modules
*-------------------------------------------------------------------
***INCLUDE MZxxxI01 .
*-------------------------------------------------------------------
*&---------------------------------------------------------------------*
*& Module PAI_EXIT INPUT
*&---------------------------------------------------------------------** text **----------------------------------------------------------------------*
MODULE PAI_EXIT INPUT.
CASE SY-DYNNR. " Interrogate screen number
Recommended