Вы находитесь на странице: 1из 33

ABAP Programming Standards - 4.

X Contents
Contents......................................................................................................................2 Document Control Sheet...............................................................................................5 Introduction.................................................................................................................6 SAP Object Naming Conventions....................................................................................7
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. Programs, Functions, Includes and Reports.................................................................7 Module Pools and Module Pool Includes......................................................................8 Function groups..........................................................................................................9 Function modules.......................................................................................................9 Transaction Codes....................................................................................................10 Development Classes................................................................................................10 Logical Databases.....................................................................................................10 Maintaining SAP Standard Objects.............................................................................10 Data Dictionary.........................................................................................................11 Authorizations...........................................................................................................12 Profiles.....................................................................................................................13 One Command One Line:..........................................................................................15 Pretty Printer:...........................................................................................................15 Variables...................................................................................................................16 Parameters ( P_ )......................................................................................................16 Parameter used as checkbox ( PX_ )and (RB_)for parameter used as radio-button....16 Select-options ( S_ ).................................................................................................16 Ranges ( R_ )...........................................................................................................16 Constants (C_ ).........................................................................................................17 Counters ( N_)..........................................................................................................17 Internal table (IT_) for Standard tables, (IS_) for Sorted tables, (IH_) for hash tables17 Structure ( X_ ).........................................................................................................18 Flags ( FG_ )............................................................................................................19 Error Messages.........................................................................................................19 Subroutines..............................................................................................................20 Literal Text:..............................................................................................................21 PF-Status..................................................................................................................22 External Files............................................................................................................22 Variants....................................................................................................................22 Messages..................................................................................................................23 Report Formatting.....................................................................................................23 Batch Data Input......................................................................................................23 Authorization Checking..............................................................................................23 Lock objects..............................................................................................................24 Debugging................................................................................................................24

Programming Standards..............................................................................................15

Code Documentation...................................................................................................25 Optimization...............................................................................................................27


1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. Avoid Dead Code:.....................................................................................................27 Logical Database:.....................................................................................................27 Techniques for efficient Database selection...............................................................27 Internal Tables..........................................................................................................37 If Condition:.............................................................................................................40 Case Statement:.......................................................................................................40 ABAP Statements......................................................................................................40 Describe Statement:.................................................................................................41 Field Length:.............................................................................................................41 Arithmetic Operators.................................................................................................41 Use of tables.............................................................................................................41 WHERE clause..........................................................................................................41 Aggregate functions..................................................................................................41 Join..........................................................................................................................42

15. 16. 17. 18. 1. 2. 3. 4. 5. 6.

Not Operator.............................................................................................................42 Minimizing the database load....................................................................................42 Standards for Specific Statements.............................................................................42 Coding Tips...............................................................................................................42 Program Structure....................................................................................................43 Screen Definitions.....................................................................................................43 GUI interfaces...........................................................................................................43 POP-UP windows.......................................................................................................43 OK_CODE (SY-UCOMM)............................................................................................44 Update......................................................................................................................44

ABAP Module Pool Standards and Practices...................................................................43

NULL VALUES.............................................................................................................44 INDEXES....................................................................................................................45 BUFFERS....................................................................................................................46 ABAP Objects..............................................................................................................48 Appendix A : Table of Application Area Code.................................................................53 Appendix B : Standard Program Structure.....................................................................54 Appendix C : Business Short, Medium, Long Names......................................................57 Appendix D : Template Screen Flow Logic Structure......................................................58
VersionDate of IssuePrepared byNameDesignation/Role-DepartmentEmail IDSignature Reviewed byNameDesignation/RoleEmail IDSignature Approved byNameDesignation/Role-DepartmentEmail IDSignature Issued/ Base-lined byNameDesignation/Role-DepartmentEmail IDSignature
After completion of each review cycle, configuration manager must increment the version number. The document history is available with the Software Quality Assurance department.

Document HistoryVersion No.Date of IssueLocation of ChangeDescription of the Change

Introduction
The ABAP language is an "event driven". The ABAP processor controls the execution of an event. For example, the event AT-SELECTION-SCREEN is executed when the user hits ENTER on the selection screen and the event STARTOF-SELECTION is executed when the user presses PF13 to start the program. Because the ABAP language incorporates many "event" keywords and these keywords need not be in any specific order in the code, it is wise to implement in-house ABAP coding standards. This document contains a list of possible ABAP coding standards, as well as some efficiency standards. Note: Customer supplied ABAP standards, if any, for a project takes precedence over this document. However, if there are no coding standards supplied by the customer, Intelligroups standards shall be used for the project. Also, if any part of the document is not relevant to the project, considering the nature of the project, then all those sections relevant to the project shall be adhered to. The programming standards being used shall be referred to in the project plan for the project. 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 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:

SAP Object Naming Conventions

Position 1 Usage:

Description "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 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 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. 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. Transaction Codes This section defines the naming conventions to be used for transaction codes (TCODE) created in the SAP system. Transaction code names will consist of Twenty (20) characters formatted as follows: This section defines the naming conventions to be used for function groups. Function group names of twenty-six (26) characters formatted as follows: Position Description 1 "Z". 2 Application Area (Ref. Appendix A) 4-20 User defined; should be meaningful for the function group Development Classes. This section defines the naming conventions to be used for development classes DEVC stored in the TDEVC 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 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 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. Data Dictionary Transparent tables. Position Description 1 Y,Z or T9 2 Application identifier 3 - 16 meaningful description 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

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

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

Check objects (Authorization Objects) Check objects are objects that are called from ABAP to check the login users authority to perform a function or check access to specific field values. Naming convention: Position Description 1 Z Required by SAP 2 Application area (Ref. Appendix A) 3 _ underscore 4-10 Use meaningful words Application 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
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
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. 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. Variables ABAP variable names can be up to 30 characters for DATA fields and subroutines and up to 8 characters for SELECTOPTIONS 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: Parameters ( P_ ) Parameters variable are used to allow data entry at the selection screen before program execution. These variables have a limited length of eight (8) characters. Variable types of this category must be prefixed with P_. The following are examples of variable names to be used. PARAMETER: P_VKORG TYPE MVKE-VKORG, P_VTWEG TYPE MVKE-VTWEG. Parameter used as checkbox ( PX_ )and (RB_)for parameter used as radio-button Select-options ( S_ ) The SELECT-OPTIONS <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. 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. Constants (C_ ) Constant variables do not change during the execution of a program. Whenever possible the literal itself should be used. These field types should be prefixed with C_. The following are examples of variable names to be used: Example: DATA: C_MATNR TYPE V_MATNR VALUE 000000000010000001, C_TRUE VALUE 1, C_FALSE VALUE 0. Counters ( N_) A counter is a variable which is incremented once for each iteration. Internal table (IT_) for Standard tables, (IS_) for Sorted tables, (IH_) for hash 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. Structure ( X_ ) Records or Structures consists of a fixed number of data objects (also called components of the record) Example: DATA: BEGIN OF X_STRUCTURE, FIELD1 LIKE SG-FIELD1, FIELD2 LIKE SG-FIELD2. FIELD1 TYPE SG-FIELD1, FIELD2 TYPE SG-FIELD2. INCLUDE STRUCTURE MARA. DATA: END OF X_STRUCTURE. DATA: X_MARA TYPE MARA. Flags ( FG_ ) Flags are variables that contain only one of two values. These variables will be defined as character of length 1. In 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 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

Message IDs Message IDs are twenty character names given to a group of related messages. The following are the naming standards by position for message IDs: 1 "Z" Required by SAP2 Application area code (Ref. Appendix A) 2 - 20 Meaningful description Message 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. 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. 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. 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 PPrevious page. 23 P+ Next page. 24 P++ Last page of document. 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. 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 Messages All Error messages are to be implemented via MESSAGE IDs (Ref. Section 2.5.1). Any text messages must use NUMBERED-TEXT, defined via include text. The purpose of this is to make any output message text language dependent.

Report Formatting 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. 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 singlethreaded nature of the batch environment. These programs are to be broken up into smaller batch programs, where appropriate. 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. Lock objects Lock objects should be created as function modules (Enqueue / Dequeue) in a customer function group. 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. 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 *----------------------------------------------------------------------* Avoid Dead Code: Avoid leaving "dead code" in the program. Remove defined fields, which are never referenced, and code, which can never be logically executed. Always perform Extended Program Check (EPC) before delivering the object. The path for EPC is ABAP editor -> Program -> Check -> Extended Program Check. Logical Database: Choose the most efficient logical database possible. Study the selection criteria and which secondary indexes are used for that view. Provide the appropriate selection criteria to limit the number of database read. Force users to provide selection criteria by evaluating the selection criteria entered on the selection screen during the AT SELECTIONSCREEN event. Remember the power of match codes / Search 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. 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. SELECT SUM( TRAME ) INTO V_TOTAL_IN_TRANS FROM MARC WHERE MATNR EQ 000101234567890123.

e.g.2 Use:

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

Instead of:

While using SELECT SINGLE


SELECT SINGLE is used instead of SELECT-ENDSELECT loop if full primary key is known. Otherwise, use SELECTup to 1 Rows. SELECT SINGLE requires one communication with the database system. Ex. Use SELECT SINGLE * FROM SCARR WHERE CARRID = 'LH'. Instead of SELECT * FROM SCARR WHERE CARRID = 'LH'. ENDSELECT.

Keep the number of data records small.


Never use Nested SELECT loops. Instead consider options: Views, Joins or select statement with for ALL ENTRIES OPTION Always use the WHERE clause in the corresponding SQL statement. An Application should read only those lines 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


Dont 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. 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 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 MANDT cust_code === Invoice Invoice_line MANDT MANDT inv_num === inv_num cust_code

Say you then have to report off this information. Your report would contain ONLY those customers which had Invoices which had at least one line. Customers without invoices would not be included. Customers that had invoices but without a line would not be included. This is the principle of the INNER join. All the data has to be there and be related. Database views support ONLY the inner join concept. Outer Joins In the majority of cases inner joins will actually be the requirement, but in the minority of cases you will want to use an outer join. Outer joins are useful where you may need all records from a certain table, that meet the selection criteria, and all data from another table(s), IF it exists. But if the latter data does not exist, you still want to get the first table data. Using our imaginary tables again. Suppose the requirement is not for an invoice report, but for a customer report, showing outstanding invoices. You want to see ALL customers, so you can't use an inner join (Incidentally therefore you can't use a database view, database views only support INNER joins) because if you did, you would not see customers that had no invoices. So you would construct an outer join relationship as under: Customer MANDT Invoice Invoice_line 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 MANDT Invoice Invoice_line 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 S~CARRID = F~CARRID AND S~CONNID = F~CONNID AND S~FLDATE = F~FLDATE. Following the above guidelines does not guarantee the most optimal selection from the database. Ultimately, it 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 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. 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. 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. 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 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. 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. 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 Move Command: When records a and b have the exact same structure, it is more efficient to MOVE a TO b than to MOVECORRESPONDING 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. 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 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. 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. 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. 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. Field Length: To find out the length of a field use the string length function. FLDLEN = STRLEN (FLD). is more efficient than IF FLD CP * #. ENDIF. FLDLEN = SY-FDPOS. Arithmetic Operators Use symbols for arithmetic operators instead of characters for better performance. Example: use <> instead of NE . 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. WHERE clause Always try to use the columns which are used in indexes in SELECT statements WHERE clause along with other nonindexed columns in the WHERE clause. 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. Join To process a join, i.e. process data from 2 or more tables use view instead of nested select statements.

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. 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. Standards for Specific Statements 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. AT PFnn Use the AT USER COMMAND instead of AT Pfnn. This ensures proper response to the user command and is more legible. CHECK Use check statements whenever possible instead of nested IFs. User Interface (GUI) GUI statuses should be used for interactive report programs and online programs. Use menu bar linking whenever possible to build consistent GUI statuses for screens within a module pool. CHECK, EXIT, REJECT, STOP & CONTINUE Use these statements to suspend processing and/or skip remaining unnecessary processing for improved performance. Coding 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). Program Structure The ABAP Programmers Workbench (SE80) should be used to create and maintain all Module Pool programs. A sample flow-logic and associated modules for all screens in a module pool is defined in Appendix D. Screen Definitions Screens are to use data dictionary fields for all variables. This does not include multiple selections like radio buttons. Screens are to be numbered with an entry screen of 100. Reuse screens whenever possible. Tab Strips: Use Tab strips wherever possible as they provide an easy way to define different application components on the same screen and switch between them. Their intuitive design also makes them easier for the end users. GUI interfaces GUI interfaces must follow SAP standards. User defined menus are to contain all actions that are applicable to the transaction. Items that are not effective during a screen process are to be disabled. Commonly used selections are to appear as push buttons below the menu bar. 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. 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). Update Never use single-line Updates. When the fields selected are part of the key, then to avoid multiple selections, use DISTINCT clause: This clause should be used when there is a large amount of data, which cannot be handled in the memory, and when there is an Index. When the data is small and there is no Index, then use DELETE ADJACENT DUPLICATES. A Null Value is an undefined value of a field in a database table. Outputs a Null Value: After an ADD FIELD field n in the database table. All existing entries get a Null Value for field n. After INSERT with a database view for the fields which are not defined in the view. When reading a field with a Null Value from the database, the result will be: SPACE for fields with type CHAR, RAW, LANG 0 for fields with type INT4, FLTP, DEC 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. Dont use too many fields. Most database systems use only a certain number of index fields. Use the most selective fields first. Create the index for the main case. Be aware that other SELECTs can cause problems. R/3 buffers are local to the application server and hold primarily run-time data.

EXES

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.

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 ABAP Objects is a new concept in R/3 Release 4.0. The term has two meanings. On the one hand, it stands for the entire ABAP runtime environment. On the other hand, it represents the object-oriented extension of the ABAP language. This documentation introduces a selection of terms that are used universally in object orientation and also occur in ABAP Objects. Classes Classes consist of ABAP source code, enclosed in the ABAP statements CLASS... ENDCLASS. For a local class, you enter this source code directly in the corresponding ABAP program. For a global class, it is generated by the Class Builder in special tables within the R/3 Repository. A complete class definition consists of a declaration part and, if required, an implementation part. The declaration part of a class <class> is a statement block: CLASS<class>DEFINITION. ... ENDCLASS. It contains the declaration for all class components (attributes, methods, events). When you define local classes, the declaration part belongs to the global program data. You should therefore place it at the beginning of the program. If you declare methods in the declaration part of a class, you must also write an implementation part for it. This consists of a further statement block: CLASS <class> IMPLEMENTATION. ... ENDCLASS. You can divide the declaration part of a class into up to three visibility areas:

CLASS <class> DEFINITION. PUBLIC SECTION. ... PROTECTED SECTION. ... PRIVATE SECTION. ... ENDCLASS. (For further details refer help on defining classes.) CLASS-DATA ( a). Declares static attributes in a class or an interface in ABAP Objects. CLASS-METHODS meth. CLASS-METHODS meth FOR EVENT evt OF cif. Declares static methods in a class or interface in ABAP Objects. CLASS-EVENTS evt. Declares static events in a class or interface in ABAP Objects. CLASS-POOL. Additions: 1. ... MESSAGE-ID mid Introductory statement for a class pool. Class pools are programs with type Class Pool that serve as containers for global classes. You cannot enter the CLASS-POOL statement in a program yourself. Instead, it is generated by the Class Builder. ReferenceVariables Objects are runtime instances of classes in the memory area of a program. A program accesses individual objects using pointers called reference variables. You declare reference variables using the statement DATA <obj> TYPE REF TO <class>. Object Instances Once you have declared an object variable <obj> for a class <class>, you can create an object using the statement CREATE OBJECT <obj>. To access the object components using the object variable <obj>, use the following syntax: To access an object attribute <attr>: < obj>-><attr> To call a method <meth>: CALL METHOD < obj>-><meth> Defining Interfaces You can define interfaces in a similar way to classes; either locally in your program, or globally using the Class Builder. The definition of an interface <ifac> consists only of a declaration part: INTERFACE <ifac>. ... ENDINTERFACE. Incorrect syntax in ABAP Objects (for details refer to help on Changes in release 4.6 - ABAP Objects - Replacement of Obsolete Statements for 4.6 )

BIT - Operations:The bit expression bitexp is calculated and the result placed in field x. You can use the four bit operators BIT-NOT, BIT-AND, BIT-XOR and BIT-OR. The operands are linked according to the table below. The priority is normal: BIT-NOT has priority over BIT-AND, followed by BIT-XOR, and then BIT-OR. You can use any number of parentheses. x y BIT-NOT x x BIT-AND y x BIT-XOR y x BIT-OR y

0 0 1 1

0 1 0 1

1 1 0 0

0 0 0 1

0 1 1 0

0 1 1 1

CATCH
Variants: 1. CATCH SYSTEM-EXCEPTIONS except1 = rc1 ... exceptn = rcn. You can catch ABAP runtime errors in the processing block enclosed in the CATCH ... ENDCATCH statements. Note the following: - rc1 ... rcn must be numeric literals. - CATCH ... ENDCATCH may be placed anywhere where IF ... ENDIF (for example) may occur. It is local, not cross-event. - It may be nested to any depth. - It only catches runtime errors in the current call level. This means, for example, that runtime errors resulting from PERFORM- or CALL FUNCTION statements are not trapped by CATCH ... ENDCATCH. (for the list of standard runtime catchable errors refer to help) COMMUNICATION:COMMUNICATION INIT DESTINATION dest ID id. COMMUNICATION ALLOCATE ID id. COMMUNICATION ACCEPT ID id. COMMUNICATION SEND ID id BUFFER f. COMMUNICATION RECEIVE ID id ...BUFFER f ...DATAINFO d ...STATUSINFO s. 6. COMMUNICATION DEALLOCATE ID id. The COMMUNICATION statement allows you to develop applications which perform direct program-to-program communication. The basis for this is CPI-C (Common Programming Interface - Coummunication), defined by IBM within the context of SAA standards as a standardized communications interface. The COMMUNICATION statement provides the essential parameters for implementing simple communication. The basis for this is the CPI-C starter set that covers the following functionality: Establishing a connection Accepting a communication Sending data Receiving data Closing a connection ABAP Tabstrip Control Basic form CONTROLS ctrl TYPE TABSTRIP. Effect Creates a control ctrl with type TABSTRIP. 1. PUT node. 2. PUT <node>. You can only use this statement in the database access program of a logical database whose structure contains the node node. You use it to pass data read by the logical database to its

user. This is either an executable (type 1) program with the logical database entered in its program attributes, or a program that is using the function module LDB_PROCESS. In the first case (executable programs), the "PUT node." or PUT <node>." statement triggers the "GET node." event in the program. In the second case, the corresponding callback routine is called, and the data from the work area node or <node> is passed back to it. STRING and XSTRING The elementary data type STRING is similar to data type C and refers to a variable-length string. Accordingly, the elementary data type XSTRING is similar to data type X and refers to a variable-length byte sequence. Area Code F D A K M V C I Q P U G S Y E X 1 N R H 9 L W J Description FI - Financial Accounting DASS (Control Station) AM - Assets Management CO - Controlling MM - Materials Management SD - Sales and Distribution PP - Production Planning PM - Plant Maintenance QM - Quality Management PS - Project System Enterprise Data Model General Ledger (G/L) Basis System EDI Cross Application Environment Health & Safety Hospital Human Resources Human Resources Planning Industry Solution Inventory Management Merchandise Management System Publishing Work Flow

*********************************************************************** * * Program name: Program name - Program title * * Description: Description of program * * Date/Author: Date Written/Authors name * * Table Updates: Listing of tables updated * * Input Parameters: (For Includes/ Function Modules) * * Output Parameters: (For Includes/Function Modules) * * Return Codes: * * Special Logic: * * Includes: ************************************************************************ *MODIFICATION LOG ************************************************************************ * Date Programmer Request # Description * ------ -------------- ------------- ---------------------------* * dd/mm/yy xxxxxxxxxxxxxx nnnnn New Program *

************************************************************************ REPORT YUPSTDS . ************************************************************************ *TABLES ************************************************************************ TABLES: ************************************************************************ *SELECTOPTIONS ************************************************************************ SELECT-OPTIONS: ************************************************************************ *PARAMETERS ************************************************************************ PARAMETERS: ************************************************************************ *DATA ************************************************************************ DATA: ** Accumulators ** ** Constants ** ** Switches ** ** Work fields ** ** Internal Tables ** ** Data structures / Strings ** ************************************************************************ *INITIALIZATION ************************************************************************ INITIALIZATION. ************************************************************************ *ATSELECTIONSCREEN ************************************************************************ AT SELECTION-SCREEN. ************************************************************************ *TOPOFPAGE ************************************************************************ TOP-OF-PAGE. ************************************************************************ *ENDOFPAGE ************************************************************************ END-OF-PAGE. ************************************************************************ *STARTOFSELECTION ************************************************************************ START-OF-SELECTION. ************************************************************************ *ENDOFSELECTION ************************************************************************ END-OF-SELECTION. ************************************************************************ *FORMS

To be determined by the clients business rules. Short Name MAT MATRL Med. Name Long Name Description MATERIAL Material

Flow Logic *------------------------------------------------------------------Process Before Output. * module SET_STATUS . " Called by all screens * Enter screen specific modules here i.e. dynamic screen locking, etc. * *------------------------------------------------------------------Process After Input. * Process fast-exit commands module PAI_EXIT AT EXIT-COMMAND. " Called by all screens * Save OK_CODE pressed module PAI_INITIALIZE. " Called by all screens * * Enter screen specific modules here i.e. Field checks, Loops, Table Controls etc. * * Process user command ( OK_CODE ) after all checks completed module USER_COMMANDS. Process Before Output Modules *------------------------------------------------------------------***INCLUDE MZxxxO01 . *------------------------------------------------------------------*&---------------------------------------------------------------------* *& Module SET_STATUS OUTPUT *&---------------------------------------------------------------------* * text * *----------------------------------------------------------------------* MODULE SET_STATUS OUTPUT. CASE SY-DYNNR. " Interrogate screen number WHEN '0100'. " Screen description for screen 100 SET PF-STATUS '100MAIN'. SET TITLEBAR '100'. WHEN '0200'. " Screen description for screen 200 SET PF-STATUS '200MAIN'. SET TITLEBAR '200'. * Add any subsequent screens ENDCASE. ENDMODULE. " SET_STATUS OUTPUT Process After Input Modules *------------------------------------------------------------------***INCLUDE MZxxxI01 . *------------------------------------------------------------------*&---------------------------------------------------------------------* *& Module PAI_EXIT INPUT *&---------------------------------------------------------------------* * text * *----------------------------------------------------------------------* MODULE PAI_EXIT INPUT. CASE SY-DYNNR. " Interrogate screen number WHEN '0100'. " Screen 0100 SET SCREEN 0 . LEAVE SCREEN. WHEN '0200'. " Screen 0200 * First process any de-queuing of entries, pop-ups to confirm data loss, etc. CASE SY-UCOMM. " Interrogate system field to find out with fast exit pressed WHEN RW. SET SCREEN 0 .

WHEN OTHERS. SET SCREEN 0100. ENDCASE LEAVE SCREEN. * Add any subsequent screens ENDCASE. ENDMODULE. " PAI_EXIT INPUT *&---------------------------------------------------------------------* *& Module PAI_INIT INPUT *&---------------------------------------------------------------------* * text * *----------------------------------------------------------------------* MODULE PAI_INIT INPUT. Error! No index entries found.* set new ok_code. SAVE_OK = OK_CODE. * clear ok_code. CLEAR OK_CODE. ENDMODULE. " PAI_INIT INPUT *&---------------------------------------------------------------------* *& Module USER_COMMANDS INPUT *&---------------------------------------------------------------------* * text * *----------------------------------------------------------------------* MODULE USER_COMMANDS INPUT. CASE SY-DYNNR. " Interrogate Screen number WHEN '0100'. " Screen 100 ( enter description ) PERFORM PROCESS_0100_OK_CODES. ( Form routine to process OK codes ) WHEN '0200'. " Screen 200 ( enter description ) PERFORM PROCESS_0200_OK_CODES. ( Form routine to process OK codes ) * Add subsequent screens ENDCASE. ENDMODULE. " USER_COMMANDS INPUT

Check tables :
The ABAP Dictionary allows you to define relationships between tables using foreign keys A dependent table is called a foreign key table, and the referenced table is called the check table. Each key field of the check table corresponds to a field in the foreign key table. These fields are called foreign key fields. One of the foreign key fields is designated as the check field for checking the validity of values. The key fields of the check table can serve as input help for the check field.

The Role of Domain Value Tables:


Prior to Release 4.0, it was possible to use the value table of a domain to provide input help. This is no longer possible, primarily because unexpected results could occur if the value table had more than one key field. It was not possible to restrict the other key fields, which meant that the environment of the field was not considered, as is normal with check tables. In cases where this kind of value help was appropriate, you can reconstruct it by creating a search help for the data elements that use the domain in question, and using the value table as the selection method.

Standard tables and sorted tables The lines are processed according to the linear index. Within the processing block, the system field SYTABIX contains the index of the current line. Hashed tables As long as the table has not been sorted, the lines are processed in the order in which you added them to the table. Within the processing block, the system field SY-TABIX is always 0.
You can react to the following control level changes: FIRST : First line of the internal table.

Last : Last line of the internal table. New <f> : Beginig of a group of lines the same contents in the field <f> and in the fields left of <f>. End <f> : End of group of lines with the same contents in the field <f> and in the fileds left <f>. SELECT-OPTIONS : You use the SELECT-OPTIONS statement to declare selection tables and create corresponding input fields on the associated selection screen. You can modify the associated text as selection text When the selection screen is processed, the values entered by the user into the input fields are assigned to the header line of the selection table and appended to the table. The position of the statement in the declaration part of the program determines the selection screen to which the input fields belong. The basic form of the SELECT-OPTIONS statement is as follows: SELECT-OPTIONS <seltab> FOR <f>.

RANGES Tables :
You can use the RANGES statement to create internal tables of the same type as selection tables. RANGES <rangetab> FOR <f>. This statement is simply a shortened form of the following statements: DATA: BEGIN OF <rangetab> OCCURS 0, SIGN(1), OPTION(2) LOW LIKE <f>, HIGH LIKE <f>, END OF <rangetab>. Internal tables created with RANGES have the same structure as selection tables, but they do not have the same functionality. Selection Tables : You use the statement SELECT-OPTIONS <seltab> for <f>. to declare a selection table in the program that is linked to the <f> column of a database table, or to an internal <f> field in the program. A selection table is an internal table object of the standard table type that has a standard key and a header line. Selection tables are used to store complex selections using a standardized procedure. They can be used in several ways. Their main purpose is to directly translate the selection criteria into database selections using the WHERE addition in Open SQL statements. In addition to selection tables that you create using SELECT-OPTIONS, you can use the RANGES statement to create internal tables that have the structure of selection tables. You can use these tables with certain restrictions the same way you use actual selection tables. Selection tables created with RANGES are not components of the selection screen. As a result, no relevant input fields are generated. Also, you cannot use a RANGES table as a data interface in program <prog> called by the following statement: SUBMIT <prog> WITH <rangetab> IN <table>. However, you can use RANGES to create the table <table> in the calling program. The main function of RANGES tables is to pass data to the actual selection tables without displaying the selection screen when executable

programs are called


Although you can use RANGES tables like actual selection tables in the WHERE clause of Open SQL statements and in combination with the IN operator in logical expressions, they are not linked to a database table. This means that RANGES tables: are not passed like selection criteria to logical databases cannot be used with the shortened form of selection tables in logical expressions cannot be used like selection criteria in GET events

Table type :
You can specify the table type <tabkind> as follows:

Generic table types


INDEX TABLE

For creating a generic table type with index access. ANY TABLE For creating a fully-generic table type. Data types defined using generic types can currently only be used for field symbols and for interface parameters in procedures . The generic type INDEX TABLE includes standard tables and sorted tables. These are the two table types for which index access is allowed. You cannot pass hashed tables to field symbols or interface parameters defined in this way. The generic type ANY TABLE can represent any table. You can pass tables of all three types to field symbols and interface parameters defined in this way. However, these field symbols and parameters will then only allow operations that are possible for all tables, that is, index operations are not allowed.

Fully-Specified Table Types


STANDARD TABLE or TABLE For creating standard tables. SORTED TABLE For creating sorted tables. HASHED TABLE For creating hashed tables. Fully-specified table types determine how the system will access the entries in the table in key operations. It uses a linear search for standard tables, a binary search for sorted tables, and a search using a hash algorithm for hashed tables.

Data Elements
Data elements in the ABAP Dictionary describe individual fields. They are the smallest indivisible units of the complex types described below, and are used to specify the types of columns in the database. Data elements can be elementary types or reference types.

Вам также может понравиться