ABAP Programming NASA
ABAP Programming NASA
Author:
Bob Johnson
1.0
Core Financials
ABAP Programming Standards and Gudelines
Sign Off
Date
Name
Signature
Change Log
Date
Version
Author
Change Description
Reviewed By
Date
Name
Page 2 of 80
Core Financials
ABAP Programming Standards and Gudelines
Table of Contents
Table of Contents.........................................................................................................................3
Overview.............................................................................................................................8
General Standards.............................................................................................................8
Attributes..............................................................................................................................9
3.1.1
3.1.2
3.1.3
3.1.4
3.1.5
3.1.6
3.1.7
3.1.8
3.1.9
3.1.10
3.1.11
3.2
Title....................................................................................................................................................9
Type....................................................................................................................................................9
Status..................................................................................................................................................9
Application.......................................................................................................................................10
Authorization Group........................................................................................................................10
Development Class..........................................................................................................................10
Logical Database..............................................................................................................................10
Screen...............................................................................................................................................10
Editor Lock......................................................................................................................................10
Fixed Point Arithmetic................................................................................................................10
Start via Variant...........................................................................................................................11
Source Code........................................................................................................................11
3.3
Documentation....................................................................................................................17
3.4
3.4.1
3.4.2
3.4.3
3.5
Text Elements......................................................................................................................19
Titles and Headings..........................................................................................................................19
Selection Texts.................................................................................................................................20
Text-Symbols....................................................................................................................................20
Variants...............................................................................................................................20
Style Guidelines...............................................................................................................21
4.1
4.1.1
4.1.2
4.2
4.2.1
4.2.2
4.2.3
4.2.4
4.2.5
4.2.6
4.2.7
Page 3 of 80
Core Financials
ABAP Programming Standards and Gudelines
5
Message Classes..................................................................................................................23
5.2
Views...................................................................................................................................23
5.3
Internal Tables:...................................................................................................................24
5.4
5.4.1
5.4.2
5.5
5.5.1
5.5.2
5.6
5.7
Field Groups.......................................................................................................................26
5.7.1
5.7.2
5.7.3
5.7.4
5.8
5.8.1
5.9
Logical Database:...............................................................................................................29
5.10
Use of Indices:.....................................................................................................................29
8.2
8.2.1
8.2.2
8.2.3
8.2.4
8.3
8.4
8.4.1
8.4.2
8.4.3
8.4.4
8.4.5
8.4.6
8.4.7
8.4.8
8.5
8.5.1
SECONDARY INDEXES..................................................................................................48
Always ensure your index is being used:.........................................................................................48
Page 4 of 80
Core Financials
ABAP Programming Standards and Gudelines
8.5.2
8.5.3
8.5.4
8.6
8.6.1
8.6.2
Quality Assurance............................................................................................................................50
CROSS-REFERENCING A PROGRAM........................................................................................50
8.7
8.8
SQL Interface.....................................................................................................................55
9.1.1
9.1.2
9.1.3
9.1.4
9.1.5
9.1.6
9.1.7
9.1.8
9.1.9
9.1.10
9.1.11
9.2
String Manipulation...........................................................................................................58
9.2.1
9.2.2
9.2.3
9.2.4
9.2.5
9.2.6
9.3
Internal Tables....................................................................................................................61
9.3.1
9.3.2
9.3.3
9.3.4
9.3.5
9.3.6
9.3.7
9.3.8
9.3.9
9.3.10
9.3.11
9.3.12
9.3.13
9.3.14
9.3.15
9.3.16
9.4
9.4.1
9.4.2
9.5
9.5.1
9.5.2
9.5.3
9.6
9.6.1
9.6.2
Typing.................................................................................................................................68
Typed vs. Untyped parameters.........................................................................................................68
Typed vs. Untyped field-symbols.....................................................................................................69
Field Conversion.................................................................................................................70
Field Types I and P...........................................................................................................................70
Constants Type F..............................................................................................................................71
Page 5 of 80
Core Financials
ABAP Programming Standards and Gudelines
9.6.3
9.6.4
9.6.5
10
Mixed types......................................................................................................................................71
Literals Type C and Type I...............................................................................................................71
Arithmetic........................................................................................................................................72
10.1
10.2
General Hints:....................................................................................................................72
10.3
Programming Tips..............................................................................................................73
11
11.1
OVERVIEW.......................................................................................................................74
11.2
11.3
Database access:.................................................................................................................75
11.3.1
11.3.2
11.3.3
11.3.4
11.3.5
11.3.6
11.3.7
11.4
ABAP Programming...........................................................................................................75
11.4.1
11.4.2
11.4.3
11.5
Analysis tools......................................................................................................................76
11.5.1
11.5.2
11.5.3
11.5.4
11.5.5
11.6
11.7
11.7.1
11.7.2
11.7.3
11.8
11.8.1
TIP: When one uses the MOVE statement,...............................................................................79
11.8.2
TIP: Use the FREE <table> command.......................................................................................79
11.8.3
TIP: When defining DATA statements........................................................................................80
11.8.4
TIP: When using the SORT statement,.......................................................................................80
11.8.5
TIP: When processing an internal table use the LOOP..............................................................80
11.8.6
TIP: When the LOOP...AT...WHERE..........................................................................................80
11.8.7
TIP: Use the BINARY SEARCH,...............................................................................................81
11.8.8
TIP: Use a BINARY SEARCH read and MODIFY....................................................................81
11.8.9
TIP: If one performs many INSERTs or DELETEs....................................................................81
11.8.10 TIP: Use the CASE statement instead of a nested IF..................................................................81
11.8.11 TIP: Always place the mot likely condition first,.......................................................................82
11.8.12 Comparison different modularization techniques.......................................................................82
11.8.12.1
Internal subroutine..............................................................................................................82
11.8.12.2
External subroutines...........................................................................................................82
11.8.12.3
Function modules................................................................................................................82
11.8.12.4
Dynpros...............................................................................................................................82
11.8.12.5
Dialog Modules...................................................................................................................82
11.8.12.6
Transactions........................................................................................................................83
11.8.12.7
Reports................................................................................................................................83
Page 6 of 80
Core Financials
ABAP Programming Standards and Gudelines
11.8.12.8
List processing....................................................................................................................83
Page 7 of 80
Core Financials
ABAP Programming Standards and Gudelines
1 Overview
The purpose of this document is to detail uniform program standards for NASA Core Financials
implementation, and to provide guidelines and useful information for programmers in the SAP
environment.
Programming standards are needed to ensure the readability and maintainability of custom development
programs and to provide a consistent and meaningful interface for the user on screens and report
output.
2 General Standards
There are several general considerations, which must be recognized in conjunction with these
programming standards. The following can be regarded as the basic rules-of-thumb for the creation of
ABAPs at NASA.
1. Changes should not be made to standard SAP development objects unless they are endorsed by SAP
or are deemed by client management to be a necessity.
If changes to standard SAP code are made, please refer to the Changes to SAP Code section.
2. Documentation for all custom developments, excluding temporary objects not for transport, will be
maintained in the Lotus Notes MDM Custom Development and Product Test databases.
3. ?product name? will be used for change management and managing SAP Corrections and Transport
through testing and approval cycles.
4. Before the creation of a new ABAP, existing programs will be reviewed to determine if they may be
used as a template or potentially fill the reporting requirement. Also, a determination should be made
regarding whether or not the report would be better served by use of the Data Warehouse.
5. All custom ABAP development objects will be named according to the NASA Core Financials
Development Naming Standards. The naming standards can be found in the Lotus Notes MDM
Document Repository under the category General Deliverables.
6. Online documentation will be utilized to describe program functionality to end users and functional
leads. ABAPs will not be transported to the System Test and Production systems without supporting
on-line documentation.
7. Proper usage of SAP online tools in addition to the ABAP Editor. These include Function Modules,
Online Documentation, Message Classes, Screen Painter, Menu Painter, Logical Databases, etc.
8. Adherence to software ergonomics and design guidelines found in the SAP Style Guide and
documented in ISO Dialogue Principals ISO9241-10.
9. Completion of all work unit deliverables supporting the program development.
Page 8 of 80
Core Financials
ABAP Programming Standards and Gudelines
3.1
Attributes
Program attributes are one of the 5 sub-objects of an ABAP program where defining attributes of
the program are set. You must maintain these before entering program code or any other subobject.
3.1.1 Title
The title should be a short concise, meaningful description. It can be up to 70 characters long
and appears in the header section of a report when it is executed.
Example:
Create BDC Session for Transaction MM01 - Create Material Master
3.1.2 Type
Specifies the type of program:
Executable Program (1) can be started without a transaction, may be executed online or in the background.
Include Program (I) contain program code which is not executable by itself. Rather
it is included in other programs by the INCLUDE statement.
Module Pools (M) contain processing steps for screen modules. They are executed
via a Transaction or a menu function.
Subroutines (S) contain common FORM routines that are called using an external
PERFORM statement.
Function Groups (F) contain Function Modules and are managed by the Function
Builder. They cannot be assigned or changed in attributes screen.
Interface Pools (J) contain interfaces and are part of the object oriented extensions
to ABAP. They are managed by the Class Builder and cannot be assigned or
changed in attributes screen.
Class Pools (K) contains classes and class methods, and are part of the object
oriented extensions to ABAP. They are managed by the Class Builder and cannot
be assigned or changed in attributes screen.
3.1.3 Status
Page 9 of 80
Core Financials
ABAP Programming Standards and Gudelines
3.1.4 Application
Optionally, you may associate the program with an Application Area. For custom
development, SAP suggests choosing either the Customer Head Office Programs or the
Customer Branch Office Programs category.
3.1.8 Screen
For report programs that use a logical database. Here you can specify the screen version of
the database program.
Selection screen versions are stored in the database include DCxyzSEL. The selection screen
version defaults to the version specified in the database access program.
Core Financials
ABAP Programming Standards and Gudelines
3.1.11 Start via Variant
If checked, the program can only be executed via a variant.
3.2
Source Code
When coding programs, it is desirable to have a consistent format for maximum readability, and
thus maintainability.
You can insert this header into the ABAP using the Insert Statement function found on
menu path Edit Pattern.
2. Introductory REPORT or PROGRAM Statement
3. Local Classes, Interfaces and Methods for Object Oriented Programming (if needed).
4. Declarative elements or TOP include(s) for declarative elements
TYPES OR TYPE-POOLS
SELECT-OPTIONS
PARAMETERS
TABLES
CONSTANTS
DATA
RANGES
Page 11 of 80
Core Financials
ABAP Programming Standards and Gudelines
FIELD-GROUPS
FIELD-SYMBOLS
5. Event elements
INITIALIZATION
AT SELECTION-SCREEN
START-OF-SELECTION
END-OF-SELECTION
TOP-OF-PAGE
END-OF-PAGE
AT LINE-SELECTION
AT PFnn
AT USER-COMMAND
Events should have a defining header to separate them from the processing logic.
Example
********************************************************************
*
START-OF-SELECTION PROCESSING
*
********************************************************************
6. Subroutines
FORM
DATA
Etc.
ENDFORM
All forms should have defining headers with a short description of what the form does at
each logical break in the code.
Example:
*-------------------------------------------------------------*
*
FORM AUART_VALUE_REQUEST
*
*-------------------------------------------------------------*
* Returns a pop-up screen with order types that are used for *
* the Sales organization, distribution channel, division. *
*
*
*-------------------------------------------------------------*
Core Financials
ABAP Programming Standards and Gudelines
Include program contents are therefore usually has quite a discrete structure:
1.
You can insert this header into the ABAP using the Insert Statement function
found on menu path Edit Pattern.
Followed by either:
2.
Declarative elements.
or
3.
Program logic
Functions
-
FUNCTION <name>.
DATA
Etc.
Function logic
ENDFUNCTION
Modules
-
Descriptive header
Example:
*----------------------------------------------------------*
*
MODULE SET_PFSTATUS OUTPUT
*----------------------------------------------------------*
* Set GUI Status based on whether the transaction is a
* CREATE< CHANGE or DISPLAY
*
*
*----------------------------------------------------------*
Screen Logic
ENDMODULE
Page 13 of 80
*
*
*
Core Financials
ABAP Programming Standards and Gudelines
Subroutines
-
Descriptive header
Example:
*-------------------------------------------------------------*
*
FORM AUART_VALUE_REQUEST
*
*-------------------------------------------------------------*
* Returns a pop-up screen with order types that are used for *
* the Sales organization, distribution channel, division. *
*
*
*-------------------------------------------------------------*
FORM <name>
DATA
Etc.
Subroutine logic
ENDFORM
You can insert this header into the ABAP using the Insert Statement function
found on menu path Edit Pattern.
2.
3.
4.
5.
Page 14 of 80
Core Financials
ABAP Programming Standards and Gudelines
3.2.5 Function Pool (Group) Programs:
Function groups programs are containers for function modules and are maintained by the
function builder. Like Module Pool programs, they only contain INCLUDE statements. They
should not be changed manually.
possess a fixed interface for data exchange, making it easier to pass input and output
parameters to and from the function module.
use their own memory area and do not share memory with the calling program.
Page 15 of 80
Core Financials
ABAP Programming Standards and Gudelines
Custom function module program structure:
1.
You can insert this header into the ABAP using the Insert Statement function found on
menu path Edit Pattern.
2.
FUNCTION statement.
3.
4.
5.
Function logic
6.
ENDFUNCTION
You can insert this header into the ABAP using the Insert Statement function
found on menu path Edit Pattern.
2.
Page 16 of 80
Core Financials
ABAP Programming Standards and Gudelines
* Returns a pop-up screen with order types that are used for *
* the Sales organization, distribution channel, division. *
*
*
*-------------------------------------------------------------*
3.
4.
5.
Subroutine logic
6.
ENDFORM
3.3
Documentation
3.3.1 Program Documentation:
ABAP code is fairly self-documenting, and the version management, object navigator and
cross-reference tools of the ABAP Workbench provide a very good technical perspective of
an ABAP and its change history. However, the purpose of changes, the specific business or
technical need being addressed may not be obvious. Also, there may be prerequisite or
follow-on activities, or precautions on the use of the program. Therefore it is prudent to
provide future programmers with documentation of the program purpose, use, changes,
enhancements, additions, and deletions.
A complete repository of the program, from requirements identification through functional
design, technical design, program documentation, test results and implementation is
maintained on the Lotus Notes MDM Change Management DB.
To aid in future maintenance and enhancement of the program, the programmer should
briefly explain the purpose, use, design, structure and any testing hints at the top of the
program. Additionally, maintain a chronological history of modification notes; with the latest
change being the last entry in the modification log. The documentation block should be
placed at the top of the main program.
Comments should be placed throughout the program to identify ABAP events, explain
program logic, and the purpose of subroutines.
Page 17 of 80
Core Financials
ABAP Programming Standards and Gudelines
3.3.1.1 Class Pool Documentation
Class pool documentation is maintained in the Class Builder. For custom classes, the
documentation should have the following format.
CL ZCL_nnnnnnnnnnnnnnnnn
Ownership:
Confidential and Proprietary
Copyright 2001, NASA
All Rights Reserved
Created by:
________
Created on:
mm/dd/yyyy.
Version:
n.n
Modification Log:
Date
01/29/2001
Programmer
Correction Description
B. Johnson DEV190001
Added
Functionality:
Description of class
Relationships:
Relationships with other classes
Example:
Example showing use of CLASS
Notes:
Special considerations
Further Information:
Where to find more informaiton
IF ZIF_nnnnnnnnnnnnnnnnn
Ownership:
Confidential and Proprietary
Copyright 2001, NASA
All Rights Reserved
Created by:
________
Created on:
mm/dd/yyyy.
Version:
n.n
Modification Log:
Date
01/29/2001
Programmer
Correction Description
B. Johnson DEV190001
Added
Functionality:
Description of class
Relationships:
Relationships with other classes
Example:
Example showing use of CLASS
Notes:
Special considerations
Further Information:
Where to find more informaiton
Page 18 of 80
Core Financials
ABAP Programming Standards and Gudelines
3.3.2 Changes and Enhancements:
If a modification is made to an existing custom ABAP program, an entry should be made in
the modification log with the date, programmers initials, correction number, change
management number (?) and brief description. Also, in the program code, a comment should
be added to the effected lines indicating the correction number.
Example:
IF SY-SUBRC NE 0.
DevK9000045
Exit.
DevK9000045
ENDIF.
DevK9000045
PURPOSE: detailed User description of the programs purpose. Include any precautions
the user should be aware of resulting from the execution of this program.
FEATURES:
-
This documentation is then available to the user at execution time through the same menu
path described above or though Program Documentation icon which is automatically added
to the report selection screen Application Toolbar in the GUI interface.
3.4
Text Elements
Each ABAP should have associated text elements and constants from the source code placed
within the Text Elements section of the ABAP Editor:
Core Financials
ABAP Programming Standards and Gudelines
3.4.3 Text-Symbols
Literal text that is printed on the report can be handled two ways. One way is to hard code
the literal in the code and give the option of maintaining Text Elements for multilingual
clients.
Example:
WRITE: / Grand Total:(001).
The advantages of this method are readability and only the text element needs to be
maintained for multilingual clients.
As a standard, use the following example.
Example:
TEXT-001 defined as Grand Total:
WRITE: / TEXT-001.
The advantage of this method is ease of maintainability if TEXT-001 is coded several times
in the program and needs to be changed.
3.5
Variants
Variants may be created for executable ABAP programs. They are sub-objects of a program and
are not shared with any other program. Variants allow you to save sets of input values for
programs that you often start with the same selections.
The naming conventions for variants are found in NASA Core Financials Development Naming
Standards.
Page 20 of 80
Core Financials
ABAP Programming Standards and Gudelines
4 Style Guidelines
4.1
The Style Guide concerns all the applicable SAP design guidelines. The SAP Style Guide is based
on platform-specific style guides such as the IBM CUA Guidelines, the Windows Style Guide or
the Apple Macintosh Human Interface Guidelines, which have been adapted and added to meet
SAPs business needs.
Stated another way, the Style Guide concerns design guidelines for the graphical user interface
(GUI) or, the presentation and interaction of the application with the active user. These guidelines
primarily pertain to the screen (window) components shown below and window navigation.
Page 21 of 80
Core Financials
ABAP Programming Standards and Gudelines
4.1.2 Work Area Design Elements
4.2
Page 22 of 80
Core Financials
ABAP Programming Standards and Gudelines
4.2.4 Online Help
Each custom program / transaction must have sufficient online help for the user to
effectively use the function. Additionally, field level help and Possible entries support should
be utilized whenever possible.
03/29/2001
Page 1
Message Classes
User and system messages used during program or report processing are organized in SAP by
Message Class and Message Number. Transaction SE91 is used to create and maintain these
Message Classes and Messages. Refer to NASA Core Financials Development Naming
Standards for details.
Messages should be used in all dialog processing and in conveying errors or processing status in
an online program execution to the user.
5.2
Views
A view is a virtual table. This is a table that is not physically stored but is instead derived from
one or more other tables.
This derivation process might involve simply transferring only certain records from a base table to
the view. More complex views can be assembled from several tables.
A view can be tailored to the needs of a specific report, making it possible to directly access
specific data. The structure of such a view is defined by specifying the tables and fields to be
contained in the virtual table. If a table contains many fields and only a few of these fields has to
be read by a report, access to the data can be simplified by creating a view containing only these
fields. By accessing the view instead of the table, significant performance enhancements can be
made.
To ensure that only semantically meaningful views are created, only tables linked by foreign key
relationships in the ABAP Dictionary can be connected in a view.
Page 23 of 80
Core Financials
ABAP Programming Standards and Gudelines
The first table to be selected is the primary table of the view. Other tables can be added. These
tables must be connected to the primary table by foreign keys. The fields to be contained in the
view can then be selected from the Base tables defined for the view.
5.3
Internal Tables:
The main purpose of this section is to examine ABAP performance and how that relates to overall
system requirements and constraints. As is most often the case, the majority of processing time
for custom developed ABAPs, (upwards of 90% in most cases), is spent in database accesses.
This is usually a result of
1. nested select statements,
2. inefficient where clauses in select statements, or
3. simply functional requirements that do not match well with SAPs table relationships.
Regardless of the cause, the use of internal tables can drastically reduce database access, and thus,
reduce report run time.
5.4
5.5
Core Financials
ABAP Programming Standards and Gudelines
The primary goal is to fill this table with the most finite list of data that can be constructed
from the select statement that will be used to populate it. In terms of nesting, each record at
a high level table can result in hundreds of records that relate to it in subsequent lower level
select statements, which is why it is so necessary to be specific.
5.6
Page 25 of 80
Core Financials
ABAP Programming Standards and Gudelines
Select vbeln posnr from vbak into xvbak
where kunnr eq i_tab-kunnr.
Append xvbak.
Endselect.
Endloop.
Free I_tab.
5.7
Field Groups
A field group combines several existing fields together under one name. You use the INSERT
statement to determine which fields belong to a field group at runtime
Example:
FIELD-GROUPS: HEADER, ORDER, PRODUCT.
Neither defining a field group (statically) using FIELD-GROUPS nor filling a field group
(dynamically) with INSERT generates more memory. Rather, there exists for each field group
element a pointer to an (existing) field.
The use of field groups is an alternative method to internal tables for data storage and loop
processing. Data selection itself does not vary whether you are using internal tables or field
groups.
Some distinguishing characteristics are the method in which they are populated, and the manner in
which you can process them. An internal table is declared through explicit definition of the
structure and an occurs statement, and is populated through appending. Field groups are declared,
then specific fields are inserted into each field group for definition. At field group population time,
the term Extract <field group> populates all fields in the field group with the current value for
those fields from within the report. There is no tangible table to see, as SAP stores the
information internally in existing SAP tables.
Page 26 of 80
Core Financials
ABAP Programming Standards and Gudelines
5.7.3 Field Group Processing
Loop processing for field groups is similar to loop processing for internal tables. This is
accomplished through the use of LoopEndloop construct. Some key differences are that
field group processing allows more flexibilty regarding sorting, resorting, control breaks, and
subtotaling and totaling functionality. A field group can be sorted and resorted by any field
or combination of fields that are declared in the header field group.
These fields are also the ones available for control breaks, i.e. at new company code, at end
of customer numberThese are all accomplished through the use of the AtEndat
construct. The fields referenced in the At statement must be contained in the Header field
group.
Page 27 of 80
Core Financials
ABAP Programming Standards and Gudelines
5.8
5.9
Logical Database:
A logical database is a predefined view of the database. This path provides a link to records that
are physically separate but functionally link. The use of logical databases in ABAP programming
takes away the need for manually creating the linking of tables through select statements,
providing all of the necessary tables are contained in the structure of the logical database.
Although these provide a major time savings for the developer, they can often pull far more data
than is actually necessary since there is no discrimination of data that is selected. When a logical
database is entered in the attributes section of the report, a predefined selection screen for the
report is generated. Additional selections can be added below the standard selection screen by the
developer and can be referenced between the appropriate Get statements for the logical database.
Page 28 of 80
Core Financials
ABAP Programming Standards and Gudelines
The fields in the where clause of the select statement must be in the same order as they appear in
the index. This is necessary since it is Oracle that decides whether or not to use the index. By
successfully using an index, one can avoid a whole table search, and thus reduce significantly the
time spent in database access.
The code changes made in the SAP Standard Programs must follow the documentation standards used
by SAP, with the addition of the correction number in the comments.
Example
*>> BEGIN OF INSERT OSS 1234567 DEVK900012
IF SY-SUBRC<> 0.
PERFORM CHECK_RFC.
ENDIF.
*<< END OF INSERT OSS 1234567 DEVK900012
Page 29 of 80
Core Financials
ABAP Programming Standards and Gudelines
Page 30 of 80
Core Financials
ABAP Programming Standards and Gudelines
8.1
ABAP Name
authors name
create date
version number
Next, place all data declarations at the top of your program. This does two important things.
The code becomes easy to read and search for table or field definitions. And the data
becomes globally available, should you need to add routines later in the program. Data that is
defined throughout the program without any forethought can cause problems when something
gets reused or redefined unnecessarily. It also breaks your train of thought when debugging
complex logic.
Following the data declarations are the event elements of the program. They should be placed
in the following order:
INITIALIZATION
AT SELECTION-SCREEN
START-OF-SELECTION
END-OF-SELECTION
TOP-OF-PAGE
END-OF-PAGE
AT LINE-SELECTION
AT PF
Page 31 of 80
Core Financials
ABAP Programming Standards and Gudelines
AT USER-COMMAND
After the event elements are the local subroutines (FORM routines) performed by the event
processing logic or from other FORMs.
8.1.2 Modularization
Usually, the main processes of an ABAP program occur at the START-OF-SELECTION or
at the END-OF-SELECTION events. Design your code so that the main processing section,
or client, controls all program action. Organize all remaining code into logical groups or
subroutines that are executed, called, performed, or passed temporary control by the client.
That is, they should all work as servers to the main processing section, of your program.
Control should always return to the client, unless errors occur that need to be amended
immediately, or in rare instances, when you need to pass explicit control to the next module.
Place the server sections of code after all event elements of the program in the normal order
they will be processed. This will make your code more readable. If a section of code is
called by several subroutines, place it after the last subroutine that calls it. When it does not
make sense to separate the code into subroutines, separate the functionally related code via
comments and blank lines to logically group sections of code that will be processed and/or
maintained together.
Core Financials
ABAP Programming Standards and Gudelines
6.
Click Copy.
Example
In your program, you need to determine the first day in the fiscal period. To do this you
choose to use the FIRST_DAY_IN_PERIOD_GET function module.
The screen below shows the Pattern Insert screen with the needed selections to insert this
function call.
This results in the following coding block being inserted into the program with all the
interface parameters identified and basic return code check coding.
CALL FUNCTION 'FIRST_DAY_IN_PERIOD_GET'
EXPORTING
I_GJAHR
=
*
I_MONMIT
= 00
I_PERIV
=
I_POPER
=
*
IMPORTING
*
E_DATE
=
*
EXCEPTIONS
*
INPUT_FALSE = 1
*
T009_NOTFOUND = 2
*
T009B_NOTFOUND = 3
*
OTHERS
=4
.
IF SY-SUBRC <> 0.
* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
*
WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
Core Financials
ABAP Programming Standards and Gudelines
to separate your code into include modules or external function modules for clarity of code
and possibly performance (different rule sets apply for tuning modules and calls). If properly
organized, you can write code in this fashion, so that data is defined throughout the program,
rather than all at the top. When coding in this fashion, use liberal comments to explain what
is going on and when and why data can be defined and freed.
If the data is to be used only within a function module or subroutine, place the definition at
the top of the routine and free the space at the end. Remember to pay close attention to rules
for global and local data definitions for programs with sub-routines, especially external
routines.
are
==>
Will require only one change when the screen numbers change.
If you need extra work fields for database fields, use SAP field names whenever possible and
use the LIKE option to ensure the data attributes match. This will also avoid maintenance
problems should the data base field change.
When naming fields, avoid the use of hyphens, since they indicate field strings and ABAP
keywords.
Instead of hard-coding text literals, use Text Elements for headers, report titles, column
headings, selection texts and numbered texts. They are easier to find and change, and only
Page 34 of 80
Core Financials
ABAP Programming Standards and Gudelines
need to be changed in one place - one time. When the same literals are used in several
programs, they are easy to copy from one program to the other, rather then cut-and-paste or
retyping of hard-coding.
When defining customer tables or internal tables:
Use the same field names as any existing SAP tables - e.g. Use MANDT, not CLIENT.
If the SAP name is confusing, use the short text (in table/DD) and comments in
DATA(ABAP) to clarify. The SELECTs, Ifs, CASE, etc. will be much easier to understand
and debug when all data fields match.
Use the same DATA ELEMENT, TYPE, DOMAIN, etc. for any fields where comparisons
will take place. Although the system will perform automatic type conversions, they are
CPU/DB intensive and results can not be guaranteed for all comparisons after data
conversion.
Page 35 of 80
Core Financials
ABAP Programming Standards and Gudelines
8.1.9 Example Program
REPORT ZRIM01 .
*************************************************************************************
***
AUTHOR:
JOHN DOE.
***
DATE:
10-15-94.
***
DESCRIPTION: THIS IS A SAMPLE PROGRAM THAT READS DATA, BUILD A TABLE
***
AND PRINTS THE DATA. SEE SAMPLE SYSTEMS MANUAL
***
SPECIFICATION #4804, PAGE 12.
***
USER AREA:
THIS PROGRAM WAS WRITTEN FOR ACCOUNTS PAYABLE.
***
***PROGRAM CHANGE LOG:
***
NAME
DATE
DESCRIPTION / REASON FOR CHANGE
***
J. DOE
10-31-95
ADD COLUMN FOR CITY TO REPORT
***
*************************************************************************************
TABLES: LFA1.
DATA: BEGIN OF MYTAB OCCURS 10,
LAND1 LIKE LFA1-LAND1,
ORT01 LIKE LFA1-ORT01,
END OF MYTAB,
BAD_REGION_COUNTER(4) TYPE P VALUE 0,
BAD_REGION_COUNTER_TOT(4) TYPE P VALUE 0.
*** BEGINNING OF MAIN PROCESSING LOGIC
***
10-31-95 ADDED CITY TO WRITE STATEMENT
SELECT * FROM LFA1.
IF LFA1-LAND1 = 'US'.
* AND LFA1-ORT01 = 'HOUSTON'.
WRITE:/ 'COUNTRY = ', LFA1-LAND1, ' CITY = ', LFA1-ORT01.
MOVE LFA1-LAND1 TO MYTAB-LAND1.
MOVE LFA1-ORT01 TO MYTAB-ORT01.
APPEND MYTAB.
IF LFA1-REGIO NE 'TX'.
PERFORM PRINT_BAD_REGION_MSG.
ENDIF.
ENDIF.
ENDSELECT.
SKIP 3.
WRITE: / 'TOTAL RECORDS WITH INCORRECT REGION CODE =',
BAD_REGION_COUNTER_TOT.
*** END OF MAIN PROCESSING LOGIC
TOP-OF-PAGE.
WRITE: / THIS IS MY REPORT.
SKIP.
END-OF-PAGE.
WRITE: / THIS IS THE END OF THE PAGE.
*---------------------------------------------------------------------*
*
FORM PRINT_BAD_REGION_MSG
*
*---------------------------------------------------------------------*
*
*---------------------------------------------------------------------*
FORM PRINT_BAD_REGION_MSG.
WRITE: / 'THE FOLLOWING RECORD HAS A BAD REGION CODE'.
WRITE: / LFA1.
ADD 1 TO BAD_REGION_COUNTER.
ADD 1 TO BAD_REGION_COUNTER_TOT.
IF BAD_REGION_COUNTER GT 25.
PERFORM PRINT_SPECIAL_MSG.
ENDIF.
Page 36 of 80
Core Financials
ABAP Programming Standards and Gudelines
ENDFORM.
*---------------------------------------------------------------------*
*
FORM PRINT_SPECIAL_MSG
*
*---------------------------------------------------------------------*
*
*
*---------------------------------------------------------------------*
FORM PRINT_SPECIAL_MSG.
SKIP 4.
CLEAR BAD_REGION_COUNTER.
WRITE: / 'TOO MANY BAD STATE CODES',
/ 'CHECK THE TABLE FOR INPUT ERRORS',
/ 'HIRE A NEW CLERK IF THIS HAPPENS AGAIN'.
ULINE /2(80).
SKIP 4.
ENDFORM.
8.2
Will work.
Always CLEAR tables at the end of a loop process to ensure data is not left in the header
and mistakenly processed with the next record(s).
Use REFRESH <table> to initialize table records, as opposed to CLEAR for table
headers.
Page 37 of 80
Core Financials
ABAP Programming Standards and Gudelines
8.2.3 MOVE-CORRESPONDING
MOVE-CORRESPONDING is good for small tables or tables where most, but not all,
fields need to be moved. When all fields need to be moved and the attributes for every field
and position are identical, move the table as a group.
MOVE-CORRESPONDING will require less maintenance for tables / fields that change
over time. However, if the table has several fields the MOVE-CORRESPONDING
statement can be very costly performance wise.
8.2.4 SORT
Do not use SORT APPENDS. It is very CPU intensive and results are often
unpredictable. At best, the statement is confusing for the average ABAP programmer.
Always specify Ascending or Descending (even though the default is Ascending) for all
SORTS, for readability and unmistakable clarity.
Always code a BY data field(s) clause with the SORT command to increase performance
and improve readability. See Performance and Tuning of ABAP Programs for examples.
8.3
Will trap the error and allow controlled actions and/or abending of the
transaction.
Break down all LOOPs, Ifs, CASE, etc. statements to their simplest form. Dont complicate via
nesting unless absolutely unavoidable. Never nest more than 3 levels deep.
Page 38 of 80
Core Financials
ABAP Programming Standards and Gudelines
Avoid the use of negative logic in IF, CASE, SELECT, etc. structures whenever possible.
Example
...
SELECT * FROM KNA1,
WHERE NOT MANDT = 001.
...
IF NOT FILEDA = FIELDB.
...
ENDIF.
==> Will both work, but is confusing when used in complex or nested structures.
...
SELECT * FROM KNA1,
WHERE MANDT NE 001.
...
IF FIELDA NE FIELDB.
...
ENDIF.
==>
8.4
Is much simpler to read and maintain, expecially when combined with other
logical conditions.
Core Financials
ABAP Programming Standards and Gudelines
ZDCIND
ZPERIOD
ZACCT
ZACCT2
ZCCNTR
INTO HEADER.
...
...
SORT.
==> Very inefficient for internal tables, however for field groups this is efficient.
The system will have to sort based on every field in the table.
SORT ASCENDING BY ZCOMP ZSORT1 ZSORT2.
==> Most effective. Will require about one-fourth the resources as the qualified
SORT above and process in a fraction of the time.
Data Element
MANDT
KUNNR
FIELDB
FIELDC
FIELDD
FIELDA
FIELDE
FIELDF
Type Length
CLNT 3
CHAR 10
CHAR 15
CHAR 15
CHAR 15
CHAR 5
CHAR 20
CHAR 15
Only FIELDE and FIELDF can be properly compressed by the data base. The other
fields, FIELDB, FIELDC, and FIELDD, cannot be compressed and therefore need more
disk space and processing resources than necessary.
If the same table is defined as follows, the data base can compress FIELDB, FIELDC,
FIELDD, FIELDE, and FIELDF, and therefore, save space and processing time every
time the table is accessed. The gains in performance become even greater if the table is
placed in a pool or cluster, or processed with foreign keys (matchcodes, etc.).
Field name Key
MANDT
*
KUNNR
*
FIELDA
*
FIELDB
FIELDC
FIELDD
FIELDE
FIELDF
Data Element
MANDT
KUNNR
FIELDA
FIELDB
FIELDC
FIELDD
FIELDE
FIELDF
Type Length
CLNT 3
CHAR 10
CHAR 5
CHAR 15
CHAR 15
CHAR 15
CHAR 20
CHAR 15
Page 40 of 80
Core Financials
ABAP Programming Standards and Gudelines
8.4.3 Use of SELECT with Transparent and Pool tables.
Familiarize yourself with the data being processed before using the SELECT statement.
Table types greatly influence how you should process data within the ABAP program.
To find out what kind of table you are working with use transaction SE12, ToolsABP
WorkbenchDevelopmentABAP Dictionary. Enter the name of the table and click on
DISPLAY to get information on the TABLE TYPE.
If the TABLE TYPE is Transparent or Pool, you should always qualify your SELECT
statement as fully as possible with the WHERE option. This includes data fields that may
not be part of the key. This allows the database to evaluate the records and return only the
records matching your selection criteria.
Example
SELECT * FROM ZZLT2
WHERE RLDNR = LDGR
AND RRCTY = 0
AND RVERS = 001
AND RYEAR = YEAR.
CHECK COMP.
CHECK ACCT.
CHECK CCNTR.
==>
Page 41 of 80
Core Financials
ABAP Programming Standards and Gudelines
Example
For cluster table, BSEG with keys MANDT, BUKRS, BELNR, GJAHR, and BUZEI:
SELECT * FROM BSEG
WHERE REBZG = BSIK-BELNR
AND BUKRS = BSIK-BUKRS
AND LIFNR = BSIK-LIFNR
AND SHKZG = S
AND KOART = K.
==> Will work, but requires a lot of available memory, buffer space, & data base time to
unpack non-keyed data for verification/inclusion. This work takes place at the data
base level and can be costly. Can overload single DB servers and slow performance
for all user.
SELECT * FROM BSEG
WHERE BUKRS = BSIK-BUKRS
AND REBZG = BSIK-BELNR.
CHECK BSEG-SHKZG = S.
CHECK BSEG-KOART = K.
==> Works more efficiently for cluster tables, especially in multiple application server
environments.
Also note the ordering of the WHERE statements to match how the keys are arranged in
the table records. This is, usually, minor in performance gain, but takes no effort during
programming, and if a lot of programs are running, can add up to a useful saving of
resources.
ZZLS2
= ZZLT2-RLDNR
ZZLT2-RRCTY
ZZLT2-BUKRS.
SELECT * FROM
WHERE BUKRS
AND BELNR =
AND GJAHR =
BSEG
= ZZLS2-BUKRS
ZZLS2-DOCNR
ZZLS2-RYEAR
Page 42 of 80
Core Financials
ABAP Programming Standards and Gudelines
AND BUZEI = ZZLS2-DOCLN.
==> Compares a NUMC 3 to a CHAR 3 field. Since this SELECT will be cycled
through several times in this nesting structure, it would be more efficient to move
the data field before processing the looping SELECT.
DATA: ZZ_TEMP_DOCLN LIKE BESG-BUZEI.
...
SELECT * FROM ZZLT2
WHERE RLDNR = LDGR
AND RRCTY = 0
AND RVERS = 001
AND RYEAR = YEAR.
SELECT * FROM
WHERE RLDNR
AND RRCTY =
AND BUKRS =
ZZLS2
= ZZLT2-RLDNR
ZZLT2-RRCTY
ZZLT2-BUKRS.
Core Financials
ABAP Programming Standards and Gudelines
SUMTOT = SUMTOT + STOCKS-VALUE.
ENDLOOP.
WRITE: / TOTAL: SUMTOT.
LOOP AT PROCUREMENT.
READ TABLE PROCUREMENT...
WRITE....
SUMTOT = SUMTOT + PROCUREMENT-VALUE.
ENDLOOP.
WRITE: / TOTAL: SUMTOT.
LOOP AT ABC.
READ TABLE ABC...
WRITE....
SUMTOT = SUMTOT + ABC-VALUE.
ENDLOOP.
WRITE: / TOTAL: SUMTOT.
LOOP AT HIERARCHY.
READ TABLE HIERARCHY...
WRITE....
SUMTOT = SUMTOT + HIERARCHY-VALUE.
ENDLOOP.
WRITE: / TOTAL: SUMTOT.
LOOP AT GROUPS.
READ TABLE GROUPS...
WRITE....
SUMTOT = SUMTOT + GROUPS-VALUE.
ENDLOOP.
WRITE: / TOTAL: SUMTOT.
==> Will work, but will need more memory & resources to hold all of the sorted tables
simultaneously until they are used. This will usually cause paging of data /
memory.
SORT STOCKS BY STOCKOBJ.
...
LOOP AT STOCKS.
READ TABLE STOCKS...
WRITE....
SUMTOT = SUMTOT + STOCKS-VALUE.
ENDLOOP.
WRITE: / TOTAL: SUMTOT.
SORT PROCUREMENT BY PROCOBJ.
LOOP AT PROCUREMENT.
READ TABLE PROCUREMENT...
WRITE....
SUMTOT = SUMTOT + PROCUREMENT-VALUE.
ENDLOOP.
WRITE: / TOTAL: SUMTOT.
SORT ABC BY ABCOBJ.
LOOP AT ABC.
Page 44 of 80
Core Financials
ABAP Programming Standards and Gudelines
READ TABLE ABC...
WRITE....
SUMTOT = SUMTOT + ABC-VALUE.
ENDLOOP.
WRITE: / TOTAL: SUMTOT.
SORT HIERARCHY BY HIEROBJ.
LOOP AT HIERARCHY.
READ TABLE HIERARCHY...
WRITE....
SUMTOT = SUMTOT + HIERARCHY-VALUE.
ENDLOOP.
WRITE: / TOTAL: SUMTOT.
SORT GROUPS BY GRPOBJ.
LOOP AT GROUPS.
READ TABLE GROUPS...
WRITE....
SUMTOT = SUMTOT + GROUPS-VALUE.
ENDLOOP.
WRITE: / TOTAL: SUMTOT.
==> Will use less memory & resources by allowing the system to fill memory with only
the data immediately needed and releasing the sorted table spaces from memory
when processing is completed.
For tables that are used repeatedly and/or by several programs, consider creating data
structures in the Data Dictionary (and accessed via TABLES statement), instead of within
the individual programs (via the DATA - ENDDATA statements). The following situations
may benefit from use of an internal table via the Data Dictionary:
- the internal table is large
- the table is accessed in the same way every time and can be set up via Data
Dictionary in a pre-sorted order
- the same internal table is used in several programs and the structure might change
over time
- the program is processing several internal tables at the same time (and therefore will
need lots of memory)
- memory usage is of big concern for the particular program being optimized.
Use the FREE statement to release the memory allocated to internal tables. The FREE
statement should follow the last statement used to process the data in the table. Be sure the
table is not called upon later in the program or by a sub-routine. Use the FREE statement if:
- the internal table is large
- the internal table is sorted and re-processed several times
- the program is processing several internal tables (and therefore will need lots of
memory)
- memory usage is of big concern for the particular program being optimized.
An unqualified LOOP AT ... WHERE is preferable to a LOOP AT ... CHECK ...
ENDLOOP. construction since you will always be reducing the number of statements to be
interpreted.
Page 45 of 80
Core Financials
ABAP Programming Standards and Gudelines
8.4.7 Processing large tables.
When dealing with a large table, you should process as much information as possible on your
first pass through the data and, if possible, eliminate any other pass through the table.
Sometimes this requires the use of internal tables or data fields to store summary totals, etc.
You must evaluate each situation to determine whether it makes sense to store this data and
pass through it separately or make another pass through the original table. Factors to
consider are:
- How large is the original table versus the sub-set that would be stored as an internal
table?
- How much storage space would be required to store the data in an internal table?
If processing only needs to take place once (e.g.- store a field for comparison in a data field),
be sure this action takes place outside of any looping structure (SELECT, LOOP, DO, etc.)
so that the processing does not repeat unnecessarily.
NAME
Doe, J.
Doe, M.
Jones, A.
Jones, B.
Jones, C.
Jones, D.
Jones, E.
Smith, A.
Smith, B.
Smith, C.
COMPANY
ABC
ABC
XYZ
ABC
ABC
XYZ
ABC
ABC
ABC
ABC
STATE
TX
OK
TX
GA
TX
GA
TX
GA
TX
OK
Core Financials
ABAP Programming Standards and Gudelines
Calling a subroutine without parameters requires minimal extra CPU time. The more
parameters you pass, the more CPU time a subroutine call requires. Passing by reference
requires less CPU time than passing by value. The amount of CPU time required to pass a
single parameter by value is dependent on the size (e.g.-field length) of the parameter.
Calling a dialog module may require considerable CPU time if large table work areas or
internal tables are to be passed.
8.5
SECONDARY INDEXES
8.5.1 Always ensure your index is being used:
A well defined and properly implemented index is one of the best performance and tuning
tools available. However, because of the diversity of various database systems, and in
particular various database optimizers, it is not possible to lay down any hard and fast rules
for creating and using database indexes. Additionally, it is impossible to guarantee the data
base optimizers will use your index. Therefore, always check to ensure the proper index is
being used.
1. Use the SQL trace transaction ST05 to turn the trace on and off.
2. Click TRACE ON.
3. Execute the transaction in question via a separate session.
4. Return to ST05 and click TRACE OFF.
5. Click LIST TRACE to view the results of your trace.
6. Click on the PREPARE, OPEN or REOPEN statement to select the SQL statement
for evaluation.
7. Click EXPLAIN to obtain the results of the SQL statement and optimizer actions.
Core Financials
ABAP Programming Standards and Gudelines
=>
=>
IN clauses are often interpreted as OR conditions and may lead to the same problems.
Indexes will not be used for IS (NOT) NULL conditions.
Most optimizers have problems with OR, NEQ and LIKE conditions.
A field in an index is only valid for use if all fields that precede it in the index definition are
fully qualified.
Example
ZTABLE is defined with a secondary index:
Field name
FIELDA
FIELDB
FIELDC
FIELDD
Type Length
CHAR 3
CHAR 3
CHAR 2
CHAR 4
SELECT * FROM
WHERE
AND
AND
=>
ZTABLE
FIELDA = 'ABC'
FIELDB = 'XYZ'
FIELDC = '12'.
=>
Will not use the index as expected and will probably invoke a full table scan based
on the primary index.
Core Financials
ABAP Programming Standards and Gudelines
3. Maintenance of the index (reorganizing, etc.) outweighs the benefits.
4. Using fields whose value for most records in the table is an initial value or has a value
that is identical in most records.
8.6
Page 49 of 80
Core Financials
ABAP Programming Standards and Gudelines
The Select reference list tells all the places in the report (program and line number)
where data base or table records are selected.
READ TABLE Reference Lists
The READ TABLE reference list tells all the places in the report (program and line
number) where a data base or table record is read.
LOOP AT Reference Lists
The LOOP AT reference list tells the names of all tables processed by LOOP AT
statements. Program name and line number give the location.
MODIFY Reference Lists
The MODIFY reference list tells all the places in the report (program and line number)
where a data base or table record is modified.
DELETE Reference Lists
The DELETE reference list tells all the places in the report (program and line number)
where a data base or table record is deleted.
MESSAGE Reference Lists
The MESSAGE reference list shows all the messages sent in the program. It also tells
you the parameters sent with the message.
SCREEN Reference Lists
The SCREEN reference list contains the names of all screens set in the report and where
(program and line number) they are set.
PF-status Reference Lists
The PF-status reference list tells you which function key statuses are set in a program.
SET/GET PARAMETER Reference Lists
The SET/GET Parameter reference list tells you which SPA/GPA parameters have been
used in the report, and where.
Field Reference Lists
With the Reference list for field option, you create a list of places (program name and
line number) that reference a given field.
8.7
Page 50 of 80
Core Financials
ABAP Programming Standards and Gudelines
A Local Private Object is exempt from the transport system and cannot be ransported. Used for
objects that will be used once and thrown away. Used for early development work that has not
been assigned a name/number/development class.
You can Lock objects prior to use via corrections to protect a group of objects you will be
working with.
If you lock an object that is part of a development object, the system attempts to lock all other
related objects. The system will list objects unsuccessfully locked.
You can Protect an object so that others may not Link corrections to it.
If you Link corrections, you must transport them together. In order to do this all of the
corrections must all be released prior to transporting.
Development Class is a collection of environment objects that are dependent upon one another
(e.g.- SD objects). If you dont require segregation of objects, you may place all CTS objects in
one Development Class (e.g.-Z01).
The Development Class specifies the consolidation and integration system for that environment.
You must match Development Classes in source and target systems, when attempting a transport.
The Environment Analyzer can generate the list of objects that belong to a Development Class.
8.8
Core Financials
ABAP Programming Standards and Gudelines
- configurations
- performance of programs with generic SELECT (e.g.- a select that qualifies only 1 of 2
key fields)
- performance of this, or other , systems based on file/buffer sizes that may now be
exceeded).
If you make changes to ABAP programs, remember to consider:
- source code
- variants
- attributes (especially logical data bases)
- documentation
- text elements
- screens/menus/Dynpros
- is the program an include module for other objects?
- does this program call other modules?
- were authority checks added or changed that will affect users?
- were changes made just for testing (code commented out, debug statements added, etc.)?
- predecessor / successor jobs or job steps.
If you make changes to Dynpro objects, remember to consider:
- screen painter
- full-screen editor
- dictionary fields
- field lists
- screen attributes
- flow logic
- ABAP modules executed
- menu painter
- status
- status lists
- list of menu bars
- menu texts of interfaces
- function key settings
- function texts of interfaces
- titles
Page 52 of 80
Core Financials
ABAP Programming Standards and Gudelines
9.1
SQL Interface
9.1.1 Select Where vs. Select + Check
88,234 microsec
4,907 microsec
Always specify your conditions in the Where-clause instead of checking them yourself with checkstatements
The database can then use an index (if possible) and the network load is considerable less
SELECT SINGLE *
4,549 microsec
4,160 microsec
If you are interested in exactly one row of a database table or view, use the SELECT SINGLE
statement instead of a SELECT-ENDSELECT loop.
SELECT SINGLE requires 1 communication (I/O) with the database system, whereas SELECTENDSELECT needs 2.
Page 53 of 80
Core Financials
ABAP Programming Standards and Gudelines
9.1.3 Select aggregates
Select Where + Check
C4A = 000.
SELECT * FROM T100
WHERE SPRSL = 00.
CHECK: T100-MSGNR > C4A.
C4A = T100-MSGNR.
ENDSELECT.
221,213 microsec
24,470 microsec
If you want to find the maximum, minimum, sum and average value or the count of a database
column, use a select list with aggregate functions instead of computing the aggregates yourself.
Network load is considerably less.
1,472,996 microsec
308,670 microsec
4,395 microsec
242 microsec
For all frequently used, read-only tables, try to use SAP buffering.
Page 54 of 80
Core Financials
ABAP Programming Standards and Gudelines
9.1.6 Column Update
Single line update
Column Update
UPDATE VERI_CLNT
SET FUNCTINT = FUNCTINT + 1.
545,008 microsec
70,487 microsec
Whenever possible, use column updates instead of single-row updates to update your database
tables.
3,749,142 microsec
121,096 microsec
For all frequently used Select statements, try to use an index. You always use an index if you
specify (a generic part of) the index fields concatenated with logical ANDs in the Select statements
WHERE clause. Note that complex WHERE clauses are poison for the statement optimizer in any
database system.
REFRESH X006.
SELECT * FROM T006 INTO X006.
APPEND X006.
ENDSELECT.
2,246 microsec
829 microsec
It is always faster to use the INTO TABLE version of a SELECT statement than to use APPEND
statements.
Core Financials
ABAP Programming Standards and Gudelines
ENDLOOP.
ENDSELECT.
2,022 microsec
1,117 microsec
If you process your data only once and memory is more a concern than performance, use a
SELECT-ENDSELECT loop instead of collecting data in an internal table with SELECT INTO
TABLE and then LOOPing through the internal table.
240,062 microsec
89,276 microsec
Use a select list or a view instead of a SELECT *, if you are only interested in specific columns of
the table.
Array insert
463,581 microsec
53,917 microsec
9.2
Whenever possible, use array operations instead of single row operations to modify the database
tables.
Frequent communication between the application program and the database system produces
considerable overhead.
String Manipulation
9.2.1 Special operators in IF (CA, )
IF CHA(200) CA '()'.
"...any actions
ENDIF.
Page 56 of 80
Core Financials
ABAP Programming Standards and Gudelines
1,263 microsec
443 microsec
Use special operators CO, CA, CS instead of programming the operations yourself.
If ABAPs statements are executed per character on long strings, CPU consumption can rise
substantially.
CONCATENATE
'Mrs.' CMA CMB 'from' CMC INTO CHA
SEPARATED BY SPACE.
100 microsec
8 microsec
If you want to delete leading spaces in a string, use the ABAP statement SHIFT LEFT
DELETING LEADING
Other construction are not as fast:
with CN and SHIFT BY SY-FDPOS PLACES, with CONDENSE is possible,
with CN and ASSIGN CLA+SY-FDPOS(LEN)
In any case, avoid using SHIFT inside a WHILE loop!
CALL FUNCTION
CONCATENATE T100-ARBGB
Page 57 of 80
Core Financials
ABAP Programming Standards and Gudelines
'STRING_CONCATENATE_3'
EXPORTING
STRING1 = T100-ARBGB
STRING2 = T100-MSGNR
STRING3 = T100-TEXT
IMPORTING
STRING = CLA
EXCEPTIONS
TOO_SMALL = 01.
194 microsec
T100-MSGNR
T100-TEXT INTO CLA.
14 microsec
Some function module for string manipulation have become obsolete and should be replaced by an
ABAP statement or functions:
STRING_CONCATENATE
CONCATENATE
STRING_SPLIT
SPLIT
STRING_LENGTH
STRLEN( )
STRING_CENTERED
WRITE TO CENTERED
STRING_MOVE_RIGHT
WRITE TO RIGHT-JUSTIFIED
66 microsec
11 microsec
I1 = STRLEN( CLA ).
DO I1 TIMES VARYING STR FROM CLA
NEXT CLA+1.
CHECK STR NE SPACE.
ADD STR-LINE TO CHECK_SUM.
Page 58 of 80
Core Financials
ABAP Programming Standards and Gudelines
ENDDO.
597 microsec
9.3
171 microsec
Use the STRLEN( ) function to restrict the DO loop to the relevant part of the field, e.g. when
determining a CHECK_SUM.
Internal Tables
9.3.1 Building sorted tables
REFRESH TAB_DEST.
LOOP AT TAB_SRC.
READ TABLE TAB_DEST WITH KEY
K = TAB_SRC-K BINARY
SEARCH.
INSERT TAB_SRC INTO TAB_DEST
INDEX SY-TABIX.
ENDLOOP.
REFRESH TAB_DEST.
LOOP AT TAB_SRC.
APPEND TAB_SRC TO TAB_DEST.
ENDLOOP.
SORT TAB_DEST BY K.
98,545 microsec
20,693 microsec
If the amount of data is small, (< 20 entries),or if you need read access to the internal table while it
is being filled, the one-step approach using READ/INSERT is the right choice.
If, however, the data amount is larger and you need read-access only to the completely filled table,
the two-step process is preferable.
REFRESH TAB_DEST.
LOOP AT TAB_SRC.
READ TABLE TAB_DEST WITH KEY
K = TAB_SRC-K BINARY SEARCH.
IF SY-SUBRC <> 0.
INSERT TAB_SRC INTO TAB_DEST
INDEX SY-TABIX.
ENDIF.
ENDLOOP.
REFRESH TAB_DEST.
LOOP AT TAB_SRC.
APPEND TAB_SRC TO TAB_DEST.
ENDLOOP.
SORT TAB_DEST BY K.
DELETE ADJACENT DUPLICATES
FROM TAB_DEST COMPARING K.
43,469 Microsec
26,259 microsec
If the amount of data is small, (< 20 entries),or if you need read access to the internal table while it
is being filled, the one-step approach using READ/INSERT is the right choice.
Page 59 of 80
Core Financials
ABAP Programming Standards and Gudelines
If, however, the data amount is larger and you need read-access only to the completely filled table,
the three-step process is preferable.
37 microsec
15 microsec
If possible, specify the key fields for read access explicitly. Otherwise, the key fields have to be
computed dynamically by the runtime system.
LOOP AT TAB.
CHECK TAB-K = KVAL.
" ...
ENDLOOP.
1,395 microsec
387 microsec
LOOP WHERE is faster than LOOP/CHECK because LOOP WHERE evaluates the
specified condition internally.
As with any logical expressions, the performance is better if the operands of a comparison share a
common type.
The performance can be further enhanced if the LOOP WHERE is combined with FROM
i1and/or TO i2, if possible.
REFRESH TAB_DEST.
LOOP AT TAB_SRC INTO TAB_DEST.
TAB_DEST[] = TAB_SRC[].
Page 60 of 80
Core Financials
ABAP Programming Standards and Gudelines
APPEND TAB_DEST.
ENDLOOP.
949 microsec
314 microsec
Internal table can be copied by move just like any other data object. If the internal table itab has a
header line, the table is accessed by itab[ ]
SORT TAB.
SORT TAB BY K.
2,026 microsec
821 microsec
The more sort key you specify the faster the program will run.
LOOP AT TAB1.
LOOP AT TAB2 WHERE K = TAB1-K.
" ...
ENDLOOP.
ENDLOOP.
I2 = 1.
LOOP AT TAB1.
LOOP AT TAB2 FROM I2.
IF TAB2-K <> TAB1-K.
I2 = SY-TABIX.
EXIT.
ENDIF.
" ...
ENDLOOP.
ENDLOOP.
394,175 microsec
10,029 microsec
If TAB1 has n1 entries and TAB2 has n2 entries, the time needed for the nested loop with the
straight forward algorithm is O(n1 * n2), whereas the parallel cursor approach takes only O(n1 +
n2) time. The above parallel cursor algorithm assume that TAB2 contain only entries that are also
contained in TAB1.
If this assumption is not true, the parallel cursor algorithm gets slightly more complicated, but its
performance characteristics remain the same.
Page 61 of 80
Core Financials
ABAP Programming Standards and Gudelines
9.3.8 Deleting a sequence of lines
Pedestrian way to delete a seq. Of lines
DO 101 TIMES.
DELETE TAB_DEST INDEX 450.
ENDDO.
3,119 microsec
128 microsec
LOOP AT TAB_SRC.
READ TABLE TAB_DEST WITH KEY
K = TAB_SRC-K BINARY SEARCH.
IF SY-SUBRC = 0.
ADD: TAB_SRC-VAL1 TO
TAB_DEST-VAL1,
TAB_SRC-VAL2 TO
TAB_DEST-VAL2
MODIFY TAB_DEST INDEX SYTABIX.
ELSE.
INSERT TAB_SRC INTO TAB_DEST
INDEX SY-TABIX.
ENDIF.
ENDLOOP.
LOOP AT TAB_SRC.
COLLECT TAB_SRC INTO TAB_DEST.
ENDLOOP.
SORT TAB_DEST BY K.
1,580,904 microsec
284,471 microsec
Core Financials
ABAP Programming Standards and Gudelines
Binary search
1,452 microsec
29 microsec
If internal table is assume to have many (>20) entries, a linear search through all entries is very
time consuming. Try to keep the table ordered and use binary search.
If TAB has n entries, linear search runs in O(n) time, whereas binary search takes only O(log2(n))
time.
798 microsec
32 microsec
If you need to access a table with diferrent keys repeatedly, keep your own secondary indices. With
a secondary index, you can replace a linear search with a binary search plus an index access.
TAB = TAB_WA.
APPEND TAB.
17 microsec
9 microsec
Core Financials
ABAP Programming Standards and Gudelines
IF TAB1[] = TAB2[].
" ...
ENDIF.
1,774 microsec
535 microsec
Internal tables can be compared in logical expressions just like other data objects.
2 internal tables are equal if
they have the same number of lines and
each pair of corresponding line is equal
If an internal table itab has a header line, the table itself is access by itab[].
parallel cursor
LOOP AT TAB1.
READ TABLE TAB2 WITH KEY
K = TAB1-K BINARY SEARCH.
IF SY-SUBRC = 0.
...
I2 = 1.
LOOP AT TAB1.
READ TABLE TAB2 INDEX I2.
IF SY-SUBRC <> 0. EXIT. ENDIF.
IF TAB2-K = TAB1-K.
Page 64 of 80
Core Financials
ABAP Programming Standards and Gudelines
ENDIF.
ENDLOOP.
" ...
ADD 1 TO I2.
ENDIF.
ENDLOOP.
28,319 microsec
9,824 microsec
If TAB1 has n1 entries and TAB2 has n2 entries, the time needed to join TAB1 and TAB2 with the
straight forward algorithm is O(n1 * log2(n2)), whereas the parallel cursor approach takes only
O(n1 + n2) time.
The above parallel cursor algorithm assumes that TAB2 is a secondary table containing only entries
also contained in primary table TAB1. If this assumption is not true, the parallel cursor algorithm
gets slightly more complicated, but its performance characteristics remain the same.
26,826 microsec
4,159 microsec
With the new DELETE variant, DELETE ADJACENT DUPLICATES, the task of deleting
duplicate entries can be transferred to the kernel.
14,491 microsec
6,496 microsec
With the new delete variant, DELETE itab [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 even more.
Page 65 of 80
Core Financials
ABAP Programming Standards and Gudelines
9.4
The performance gained when using DELETE itab FROM, instead of LOOP AT itab WHERE
DELETE itab. ENDLOOP.increases with the number of entries the internal table contains and the
number of lines to be deleted.
Typing
9.4.1 Typed vs. Untyped parameters
Untyped parameters
Typed parameters
REPEAT
DIMID
ZAEHL
ISOCODE
ANDEC
PRIMARY.
* Identical source code left and right:
DO REPEAT TIMES.
T006-DIMID = DIMID.
T006-ZAEHL = ZAEHL.
T006-ISOCODE = ISOCODE.
T006-ANDEC = ANDEC.
T006-PRIMARY = PRIMARY.
I1
= REPEAT - SY-INDEX.
ENDDO.
ENDFORM.
228 microsec
161 microsec
If you specify the type for formal parameters in your source code, the ABAP compiler can optimise
the code more thoroughly. In addition, the risk of using the wrong sequence of parameters in a
PERFORM statement is much less.
If you have large untyped programs, use the automatic typing facility of the development
workbench.
Typed field-symbols
FIELD-SYMBOLS: <F>.
ASSIGN I1 TO <F>.
I2 = <F>.
I3 = <F>.
I4 = <F>.
ASSIGN I1 TO <I>.
I2 = <I>.
I3 = <I>.
I4 = <I>.
11 microsec
7 microsec
Page 66 of 80
Core Financials
ABAP Programming Standards and Gudelines
If you specify the type of field-symbols and formal parameters in your source code, the ABAP
compiler can better optimise the code.
9.5
If, Case,
9.5.1 If vs. Case
If
Case
CASE C1A.
WHEN 'A'. WRITE '1'.
WHEN 'B'. WRITE '2'.
WHEN 'C'. WRITE '3'.
WHEN 'D'. WRITE '4'.
WHEN 'E'. WRITE '5'.
WHEN 'F'. WRITE '6'.
WHEN 'G'. WRITE '7'.
WHEN 'H'. WRITE '8'.
ENDCASE.
16 microsec
7 microsec
Perform I Of
11 microec
6 microsec
A very fast way to call a certain routine using a give index is to PERFORM I OF statement.
Case
I1 = 0.
DO.
IF C1A NE SPACE. EXIT. ENDIF.
ADD 1 TO I1.
IF I1 GT 10. C1A = 'X'. ENDIF.
ENDDO.
I1 = 0.
WHILE C1A = SPACE.
ADD 1 TO I1.
IF I1 GT 10. C1A = 'X'. ENDIF.
ENDWHILE.
Page 67 of 80
Core Financials
ABAP Programming Standards and Gudelines
8 microsec
9.6
6 microsec
If you can use WHILE instead of a DO+EXIT construction, then do so. While is easier to
understand and faster to execute.
Field Conversion
9.6.1 Field Types I and P
Type P
Type I
DATA: IP TYPE P.
DO 5 TIMES.
IP = SY-INDEX * 2.
READ TABLE X100 INDEX IP.
ENDDO.
DATA: IP TYPE I.
DO 5 TIMES.
IP = SY-INDEX * 2.
READ TABLE X100 INDEX IP.
ENDDO.
78 microsec
37 microsec
Constant type F
DATA:
FLOAT TYPE F.
CONSTANTS:
PI TYPE F VALUE '3.1415926535897932'.
FLOAT = '3.1415926535897932'.
DATA:
FLOAT TYPE F.
FLOAT = PI.
22 microsec
1 microsec
Use correctly typed constants instead of literals
Only 1 type
F3 = F1 * F2.
46 microsec
Dont mix types unless absolutely necessary.
1 microsec
Type I
Page 68 of 80
Core Financials
ABAP Programming Standards and Gudelines
SY-SUBRC = '0'.
CASE SY-SUBRC.
WHEN '1'.
WHEN '2'.
WHEN '3'.
WHEN '4'.
ENDCASE.
SY-SUBRC = '0'.
CASE SY-SUBRC.
WHEN '1'.
WHEN '2'.
WHEN '3'.
WHEN '4'.
ENDCASE.
14 microsec
6 microsec
use numeric literals or named constants with a number type instead of character strings if you are
dealing with type I or integer type P fields.
9.6.5 Arithmetic
Type N
Type P
DATA:
N1(15) TYPE N VALUE '123456789012345',
N2(15) TYPE N VALUE '543210987654321',
N3(15) TYPE N.
DATA:
P1 TYPE P VALUE '123456789012345',
P2 TYPE P VALUE '543210987654321',
P3 TYPE P.
N3 = N1 + N2.
P3 = P1 + P2.
29 microsec
8 microsec
Page 69 of 80
Core Financials
ABAP Programming Standards and Gudelines
1. Initialization Event This event is executed before the output of the selection screen. The INITIALIZATION section is
only performed when the ABAP is started directly, and is not executed if the ABAP is called or
executed by another ABAP. This event is also ignored in a batch environment. It is frequently used
to calculate special defaults for the selection screen.
2. Table Loop Whenever looping on a table, always CLEAR the table header or fill it with a generic key before
the LOOP statement.
3. Structured And Modular Programming Techniques
The use of structured and modular programming techniques, along with extensive but reasonable
comments, greatly enhances the readability and maintainability of a program.
- Make use of CASE structures in place of extensive nested IFs
- Use PERFORMS to modularize the mainline area of the report
- Replace blocks of code within an extensive IF statement with a PERFORM
- Whenever possible, use the PERFORM command with the USING or CHANGING keywords
Page 70 of 80
Core Financials
ABAP Programming Standards and Gudelines
Preliminary Version
11.1 OVERVIEW
The purpose of this document is to provide ABAP programmers with the necessary information to
create performance efficient ABAP code.
Core Financials
ABAP Programming Standards and Gudelines
1. Database access
2. ABAP programming analysis
The chronological structure of this note reflects the procedure for tuning and increasing performance.
100% buffer
Generic buffer
Single record buffer
Consider creating views in database to join tables vs. join them in ABAP
Use ARRAY insert, delete, update whenever possible. See note 3.
Page 72 of 80
Core Financials
ABAP Programming Standards and Gudelines
11.4.1 Processing internal tables
If possible, index access or binary search
Avoid nested loops
Cancel loop processing
Instead of frequent sorts, fill table with sorted entries
READ the internal table with BINARY SEARCH, then INSERT with that SY-TABIX.
Consider OCCURS parameter
11.4.2 Modularization
Dialog modules
Function modules
Subroutines, e.g. FORM
While the above techniques can make your code more readable and modularized,
sometimes it will cost more CPU time. See note 3 for more information.
Hit lists
Number of conversions
Flow trace
Table access
Page 73 of 80
Core Financials
ABAP Programming Standards and Gudelines
You can quickly get a general idea of the coding run during the program execution and
of its execution time. For the evaluation, hitlists of the top CPU consumers, of the
table accesses as well as of the respective program run are available.
Page 74 of 80
Core Financials
ABAP Programming Standards and Gudelines
11.7 Note II: Performance & Load Balancing for Batch Input
11.7.1 Background of SAP BDC programs
Usually SAP BDC programs, such as RFBIBL00, are used to load high volume of data into R/3
database. Several major steps are involved:
read data from a ASCII file into BDC queue
the BDC sessions are processed in either foreground or background
1. the corresponding transaction is invoked
2. each screen field in the transaction is then filled from the BDC queue
3. foreign key checking, data validation ... etc are performed in order to maintain data
integrity
4. if input data is valid, the database updates are then perform. otherwise, the entry is
marked with error and remain in the BDC queue.
Core Financials
ABAP Programming Standards and Gudelines
try keep the destination operands as the same data type as the 'from' operands.
REASON:
Internally the system will need to covert the 'from' operand to the same data
type as the destination operand. This causes additional steps to be executed internally.
11.8.2 TIP:
once the program has completed using the table. If the program ends on completion of the table
processing, this is obviously not required.
REASON:
Each internal table takes up memory space. This memory is finite and cannot
be dynamically extended. By freeing the memory used by an internal table other internal tables
within the program can use this space and not abend because of the memory constraints.
Page 76 of 80
Core Financials
ABAP Programming Standards and Gudelines
Please Note: If a variable is defined within a FORM it is only defined to that FORM and
cannot be referenced outside the FORM. Multiple FORMs can use the same variable name
without any contention.
11.8.4 TIP:
always specify the sort key. Try keep the key as short as possible.
REASON:
When a table is sorted the key is loaded into a separate memory area. If the
key is not specified the entire row is used as the key. Here again the memory space is finite and
if the number of entries * the key is too large the program will swap to disk memory
constraints. If a key is specified, only the fields which form part of this key * the number of
entries in the table are loaded into memory. This allows for additional table entries to be sorted
and makes the sort quicker as the number of fields forming the key are less than the entire row.
11.8.5 TIP:
instead of an SQL select statement. When using the LOOP statement use the
LOOP...AT...WHERE instead of a LOOP...AT...CHECK.
REASON:
An SQL select has to first set-up an equivalent to the LOOP statement
internally. By using the WHERE clause instead of a CHECK statement within the loop the
program does not need to process each table entry, it will just process when the WHERE
parameter is met. Always clear the header before looping through an internal table using the
WHERE clause.
11.8.6 TIP:
is used ensure the condition variables have been defined with the same data type.
REASON:
Each time a row is read, internally the field(s) which form part of the WHERE
clause will have to be converted to the same data type as the condition field.
11.8.7 TIP:
when performing an direct read on an internal table. This only becomes beneficial for tables
with more than 500 rows.
REASON:
A BINARY SEARCH will break a table into logical units based in the key
defined. This will allow the read to jump through the table to find the required entry instead of
reading each table entry until the required entry is found.
11.8.8 TIP:
instead of COLLECT if the internal table is large (more that 1000 entries)
Page 77 of 80
Core Financials
ABAP Programming Standards and Gudelines
REASON:
The COLLECT statement will scan through an entire table looking for a like
entry and collate the packed fields values. If there is no match the entry will be added to the
end. For large tables adding entries to the end or collating like entries could take a long time.
By using BINARY SEARCH read the entry will be found without scanning from the beginning
of the table and the entry can be manually updated with the MODIFY command. If the entry is
not found (SY-SUBRC NE 0) the APPEND command can be used to add the entry to the table.
Remember the COLLECT statement only collates packed fields.
11.8.9 TIP:
on a large internal table, EXPORT the table to memory and IMPORT back from memory
before looping through the table.
REASON: When one performs either an INSERT or a DELETE, the physical structure does
not change and an index table is created. This table contains the pointer to the address in the
internal table created by the ABAP program. If one INSERTs a record, physically the entry is
placed at the end of the table, but the pointer to that record is inserted into the index table in the
correct position. When a row is DELETED, physically the entry remains in the internal table,
but the address is removed from the index table. When one loops through the internal table
after DELETEs or INSERTs, ABAP will loop sequentially through the index table and perform
direct reads on the internal table. By performing an EXPORT and then an IMPORT the internal
table is loaded into memory and reloaded in the correct sequence and the index table is deleted.
This way, when one loops through an internal table, there is no intermediary index table and the
loop is performed directly on the internal table.
11.8.10TIP:
REASON:
It is far quicker to read down through a CASE statement that to check the
conditions for each IF statement within a nested IF.
11.8.11TIP:
when using the IF or CASE statement. When using IF...OR have the most common success
condition first. If using IF...AND then specify the most frequent knock-out criterion first.
REASON:
If the most likely condition is not placed first then the program always has to
test the unlikely condition(s) before reaching the most likely one(s). More complex logical
expressions are valuated from left to right.
Please note that for tips 11 & 12 one must note the special features of type conversion as
mentioned in tip 1. The operands to be compared should always be of the same data type, as it
will otherwise be necessary to convert them first.
Core Financials
ABAP Programming Standards and Gudelines
Cost/Run-time: Factor 1 (Note: This is the base factor for the techniques to follow)
11.8.12.4 Dynpros
e.g. CALL SCREEN
For each CALL SCREEN command the entire dynpro needs to loaded into memory.
Cost/Run-time: Factor 148
11.8.12.6 Transactions
e.g. CALL TRANSACTION
When one calls a transaction, the system opens a new internal session or replaces the
current session with a new session (depends in syntax used). A module pool with
dynpros is allocated to a transaction. Transactions are called in a different way from
dialog modules.
Cost/Run-time: Factor 8000
11.8.12.7 Reports
e.g. SUBMIT <report-name> ...
When you start a report with the SUBMIT statement, the system opens a new internal
session or replaces the current session with a new session (depends on syntax used).
Internal tables can be passed to the submitted program.
Cost/Run-time: Factor 10000
Page 79 of 80
Core Financials
ABAP Programming Standards and Gudelines
From the above one should avoid calling dialog modules at all times. When calling transactions or
submitting reports try avoid the RETURN option. Avoid multiple or nested calls or submits within the
same program.
Page 80 of 80