Application Development Discussions
Join the discussions or start your own on all things application development, including tools and APIs, programming models, and keeping your skills sharp.
cancel
Showing results for 
Search instead for 
Did you mean: 

coding standards

Former Member
0 Kudos

Hi Guys,

i work for a company which is just a year old.

I have been asked to prepare a document on coding standards for SAP Scripts and Smartforms. I have to give a presentation on this tomorrow morning. Please help urgently.

All helpful answers will be rewarded generously.

9 REPLIES 9

Former Member
0 Kudos

just refer to this link

<a href="http://sap.niraj.tripod.com/id33.html">Coding standards</a>

Please reward if useful.

Former Member
0 Kudos

Hi,

Have a look at this coding standards.This is a demo standard for scripts and smartforms.

•Form – SAPScript & SmartForm

Z<Application area>F_<Text to represent use>_nn

Where nn is sequential number between 01 to 99

•Form – Style & SmartStyle

Z<Application area>F_<Text to represent use>_nn

Where nn is sequential number between 01 to 99

•Standard texts

Z<Application area>TX[_<Text to represent use>]_nnnn

Where nn is sequential number between 0001 to 9999

Mark all helpful answers.

Former Member
0 Kudos

hi hope this helps you,

Program Naming Standards

position 1 -> Z

position 2 -> 1 Character Module Identification

position 3 -> 1 Character showing Type of Program ( report , smart forms )

position 4-6 -> Development number under each Area (R/3 module). To be assigned by Project Manager.

position 7 -> '_'

position 8-20 -> Any free format text which gives key information about the program

program coding standards

Use your own paragraph standard rather than using the existing paragraph standards , same is for character standard .

sreeramkumar_madisetty
Active Contributor
0 Kudos

Hi

Refer the link:

http://sap.niraj.tripod.com/id33.html

Regards,

kumar

Former Member
0 Kudos

p347633,

Pls. check

http://web.mit.edu/ist/org/admincomputing/dev/zprogdoc.htm

SAP Object Naming Conventions

This section defines the naming conventions for the following object types found in the SAP environment:

Programs, Functions, Includes, and Reports

Module Pools, Module Pool Includes

Function Groups, Modules

Transaction Codes

Development Classes

Logical Databases

SAP Standard objects

Data Dictionary elements

1. Programs, Functions, Includes and Reports

This 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.

"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 Description

1 ‘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 modules

Fnn; 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

2. Module Pools and Module Pool Includes

This 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 code

Module 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

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

3. Function groups

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)

User defined; should be meaningful for the function group

Function groups should contain related function modules and have the global interface flag turned off.

4. 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. This is mandatory if the function module being created is to be used for RFC interfaces.

5. 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

6. Development Classes.

This section defines the naming conventions to be used for development classes DEVC stored in the TDEVC table. Development 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

7. 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 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 Alphanumeric identifier (0 – 9, A – Z)

3 Application Area (Ref. Appendix A)

4 - 14 Meaningful Alphanumeric identifier

15 – 20 Reserve for future

8. Maintaining SAP Standard Objects

The 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 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 remains 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 customized code must be called. The include module must indicate (in the documentation) its purpose and location where it is called from.

9. Data Dictionary

Transparent tables.

Position Description

1 Y,Z or T9

2 Application identifier

3 - 16 meaningful description

1. Views

Views 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 VIEW

9 – 16 meaningful name

2. Structures

The following naming convention is to be used for structures, by position:

Position Description

1 Z, Y, T9 required by SAP

2 Application identifier

4 –10 STRUCT

11 – 30 Meaningful description

3. Domains

Domains define the physical attributes of a field. Domains can be checked against value tables or be assigned a check table 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 Description

1 Z & Y

2 Application identifier

4 – 7 DOM

8 – 30 Meaningful name

Example:

ZM_DOM_MATERIAL

4. Data Elements

Data 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

5. Fields

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.

10. Authorizations

1. Object Class

An authorization object class, groups common check objects together in a logical group. Authorization class has a length of four (4) characters and should be defined as follows:

Position Description

1 ‘Z’

2-4 3-character short business name

2. Check objects (Authorization Objects)

Check objects are objects that are called from ABAP to check the login user’s 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

3. Application Area

Authorizations 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 ‘_’ underscore

4-10 Use meaningful words

Alternative naming convention (Release 2.2):

Position Description

1 Application area (Ref. Appendix A)

2 ‘:’ Colon

Use meaningful words

11. Profiles

Profiles 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 ‘_’ underscore

4-10 Use meaningful words

Alternative naming convention (Release 2.2):

Position Description

1 Application area (Ref. Appendix A)

2 ‘:’ colon

Use meaningful words

Programming Standards

1. One Command One Line:

Each ABAP command consists of a sentence ending with a period. Multiple commands can be on one line; however, as a standard start each new command on a new line. This will allow for easier deleting, commenting, and debugging.

2. 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.

3. Variables

ABAP 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’ parameter should be used to define work fields.

Ex. DATA: V_MATNR TYPE MARA-MATNR.

All program variables should use the following prefixes:

4. 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.

5. Parameter used as checkbox ( PX_ )and (RB_)for parameter used as radio-button

6. Select-options ( S_ )

The SELECT-OPTIONS <Field name> for <Table field> 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 <variable>-high value, <variable>-low value, <variable>-sign, and <variable>-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.

SELECT-OPTIONS: S_MATNR FOR V_MATNR.

7. Ranges ( R_ )

The RANGES <Field name> for <Table field> statement generates a program variable used for selection criteria much like the SELECT-OPTIONS. The variable generated is actually a system-generated table containing <variable>-high value, <variable>-low value, <variable>-sign, and <variable>-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.

8. 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’.

9. Counters ( N_)

A counter is a variable which is incremented once for each iteration.

10. Internal table (IT_) for Standard tables, (IS_) for Sorted tables, (IH_) for hash tables

TYPES <t> TYPE|LIKE <tabkind> OF <linetype> [WITH UNIQUE/NON-UNIQUE <key>]

[INITIAL SIZE <n>] {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,

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 declaration

The ‘CLEAR <tab>‘ should be used to initialize the table header record.

The ‘REFRESH <tab> ‘ should be used to delete all table entries and release any paged out area. It is recommended that before a table is used; perform a REFRESH then a CLEAR in this order. A REFRESH does not clear the header record.

The ‘FREE <table>‘ 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.

11. 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.

12. Flags ( FG_ )

Flags are variables that contain only one of two values. These variables will be defined as character of length 1. In all cases, 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

13. Error Messages

The 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 Severity

Message Number

a) Message ID’s

Message ID’s are twenty character names given to a group of related messages. The following are the naming standards by position for message ID’s:

1 "Z" Required by SAP2 Application area code (Ref. Appendix A)

2 – 20 Meaningful description

b) Message Severity

Message severity defines the action performed upon execution of the message. The following are the allowable message severity 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

Message numbers are the unique 3-character identifiers of a message. Message numbers range for 001 to 999. The next available should be used.

14. Subroutines

If 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.

15. 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.

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.

16. PF-Status

PF 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 are not 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.

17. External Files

External 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.

18. Variants

Variants 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 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

8 Underscore "_"

9 "V" for variant.

10-14 Meaningful information

19. Messages

All Error messages are to be implemented via MESSAGE ID’s (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.

20. Report Formatting

Blank lines are to be specified using ‘SKIP <n>‘ 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.

21. Batch Data Input

Batch 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.

22. Authorization Checking

Authorization 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.

23. Lock objects

Lock objects should be created as function modules (Enqueue / Dequeue) in a customer function group.

24. Debugging

All 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.

Code Documentation

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:-

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

----


Optimization

1. 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.

2. 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 SELECTION-SCREEN event. Remember the power of match codes / Search Helps for 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.

3. Techniques for efficient Database selection

The 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

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 MARA

WHERE 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 SELECT…up 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 of 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

INTO TABLE IT_MARA

FROM MARA

WHERE MATNR LIKE ‘23%’.

Option 2

E.g. SELECT MATNR

INTO MARA-MATNR

FROM 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 index corresponds 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 assists selection only up until the first unspecified field. Fields should be included in an index only if they significantly restrict 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? ).

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_MARC

WHERE 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; Invert 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.

<Process plant>

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, <process plant> 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.

There are two ways to get ordered data. The data can be selected using the addition ORDER BY from the database. This 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

1. Don’t use identical select statements.

Use option 1 instead of option 2.

Option 1

e.g. To get Material Descriptions

LOOP AT IT_VBAP.

READ TABLE IT_MAKT KEY MATNR = IT_VBAP-MATNR TRANSPORTING MAKTX

IF 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 2

e.g. To get Material Descriptions

LOOP AT IT_VBAP.

SELECT SINGLE MAKTX INTO IT_VBAP-MAKTX WHERE MATNR EQ IT_VBAP-MATNR.

ENDLOOP.

2. 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 BUFFER

Any 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

3. 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, and if 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

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_num

cust_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.

4. 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_num

cust_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 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 F

WHERE 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

SCARRID = FCARRID AND

SCONNID = FCONNID AND

SFLDATE = FFLDATE.

Following the above guidelines does not guarantee the most optimal selection from the database. Ultimately, it depends on 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 completed

All 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

4. Internal Tables

The 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.

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.

1. INITIAL SIZE <n>

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 <n> 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 memory areas 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 <= <n> <= 100.

2. Collect Statement:

When working with internal tables, remember that the COLLECT statement can be very CPU intensive. When Collecting on an internal table with greater than 50-60 entries, use the following alternative code.

READ TABLE ITAB WITH KEY NEW-KEY BINARY SEARCH.

CASE SY-SUBRC.

WHEN 0. NEW-AMT = NEW-AMT + ITAB-AMT.

MOVE ...

MODIFY ITAB INDEX SY-INDEX.

WHEN 4. MOVE ...

INSERT ITAB INDEX SY-INDEX.

WHEN 8. MOVE ...

APPEND ITAB.

ENDCASE.

For internal tables with less than 50 entries the COLLECT is more efficient.

Do not perform any of the following functions when internal table is populated using Collect statement:-

Append, Insert, Modify, Delete, Sort, Refresh, Import, Select into table/appending table. They invalidate the collect statement.

3. Read Table:

When reading a single record in an internal table, the READ TABLE WITH KEY is not a direct READ. Therefore, SORT the table and use READ TABLE WITH KEY BINARY SEARCH. Always read the required fields using TRANSPORTING f1 f2 …

4. Sort Statement:

SORT <itab> [Ascending/Descending] [As text] [Stable]

By <f1> Ascending/descending [As text]

By <fn> Ascending/descending [As text]

As text is used to sort the table alphabetically.

When Sorting internal tables, specify the fields to be Sorted.

SORT ITAB BY FLD1 FLD2. is more efficient than SORT ITAB.

Sorting an Internal Table, though done in the memory, is a unnecessary load on the processor. Try to fill the table with sorted values. If the SORTED BY clause cannot be used in the select statement, then Sorting the Internal Table is inevitable.

5. APPEND <wa> to <itab> SORTED BY <f>

Use only SORTED clause when:

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 <itab1> [FROM <n1>] [TO <n2>] TO <itab2>

When appending fixed lines from an internal table to a new internal table.

6. MOVE

Avoid 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

7. 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 than

MOVE-CORRESPONDING BSEG TO *BSEG.

Note: avoid unnecessary MOVEs by using explicit work area operations.

8. 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 <itab> COMPARING F1 F2 …

5. 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 first and for the OR, place the most likely true first.

6. Case Statement:

When testing fields "equal to" something, one can use either the nested IF or the CASE statement. The CASE is better 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.

7. ABAP Statements

The 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

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.

8. Describe Statement:

DESCRIBE TABLE <itab> [LINES <l>] [OCCURS <n>] [KIND <k>]

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.

9. 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.

10. Arithmetic Operators

Use symbols for arithmetic operators instead of characters for better performance.

Example: use <> instead of NE .

11. Use of tables

Internal 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.

12. WHERE clause

Always 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.

13. Aggregate functions

Use of aggregate functions in the SELECT expression list to find the minimum, maximum, count and average list instead of computing it yourself.

14. Join

To process a join, i.e. process data from 2 or more tables use view instead of nested select statements.

15. Not Operator

The 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.

16. Minimizing the database load

Do 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, let 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.

17. Standards for Specific Statements

1. ASSIGN

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.

2. AT PFnn

Use the ‘AT USER COMMAND’ instead of ‘AT Pfnn’. This ensures proper response to the user command and is more legible.

3. CHECK

Use check statements whenever possible instead of nested IF’s.

4. 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.

5. CHECK, EXIT, REJECT, STOP & CONTINUE

Use these statements to suspend processing and/or skip remaining unnecessary processing for improved performance.

18. Coding Tips

A 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 of

LOOP AT ITAB.

CHECK ITAB-NAME1 = KVAL.

ENDLOOP.

ABAP Module Pool Standards and Practices

The 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 ABAP features 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).

1. 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.

2. 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.

3. 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 to appear as push buttons below the menu bar.

4. POP-UP windows

Pop-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.

5. 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 (Exists as the last field in the field l).

6. Update

Never use single-line Update’s.

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.

NULL VALUES

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, DEC

INDEXES

The 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.

Don’t 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.

BUFFERS

R/3 buffers are local to the application server and hold primarily run-time data.

a) Buffer types:

Table buffers for resident, generic and partially buffered tables

Number 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 as generic 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.

b) SQL statements bypassing buffer

All 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)

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. An exception 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

Pls. reward if useful

Former Member
0 Kudos

hi guys,

if you go to the documentation part of nay form there you'll see something called as ELEMENT. what is this for. please reply. points will be awarded generously.

Former Member
0 Kudos

hi guys what are standard texts in sap scripts. please reply urgently.

0 Kudos

Hi p347644,

1. standard texts are similar to sapscript.

2. Hence, the coding standard there would also be same as sapscript.

regards,

amit m.

Former Member
0 Kudos

Hi

Did you get any document on ABAP coding stds for scripts and smartforms.

regards

sri