ABAP Program Standards

Embed Size (px)

Citation preview

  • 8/2/2019 ABAP Program Standards

    1/20

    Programming Standards

    DocumentChangeControl

    Release Description CreatedBy

    Date ReviewedBy

    Date Approved Date

    1.0 First relese KannanGopal

    1.1 Changes to the Indiadevelopment andauthorization check

    KannanGopal

    CONTENTS1 Overview

    2 Naming conventions

    3 Development Guidelines

    4 Documentation Within the Code

    4.1 Program Header

    4.2 Subroutines

    4.3 Events

    4.4 Modules

    4.5 Module Pool Programs

    4.6 Function Pool ( Group ) Programs

    4.7 Subroutine Pool Programs

    4.8 Class Pool Documentation

    4.9 Interface Pool Documentation

    4.10 Changes and Enhancements

    4.11 User Documentation

    4.12 Text Elements

    Page 1 of 20

  • 8/2/2019 ABAP Program Standards

    2/20

    Programming Standards

    5 Message Classes

    6 Changing SAP Code

    7 Database tables

    8 Database Updates

    8.1 Database Operations ( SQL)

    8.2 Open SQL VS . Native SQL

    8.3 Join

    8.4 Indexes

    8.5 Subqueries

    8.6 Accessing data in Packages

    8.7 SAP Index tables

    9 Usage of Internaltable types

    9.1 Defining Internal Tables

    9.2 Working with Internal Tables

    10 Function Module Exception Handling

    11 Reusing Existing Data Elements /Domains vs . Creating New Ones

    12 Adding Customer Fields to SAP Delivered Tables

    13 Data Elements in the Data Dictionary14 Program Layout

    15 Parameters and Selection Screen Fields

    16 Localvs . GlobalVariables

    17 Modularization

    17.1 Subroutines and Function Modules

    17.2 Function Groups

    18 Authorization Check

    19 Country Specific development

    Page 2 of 20

  • 8/2/2019 ABAP Program Standards

    3/20

    Programming Standards

    Overview

    The purpose of this document is to detail uniform program standards for ABB and to provide guidelines anduseful information for programmers in the SAP environment.

    Programming standards are needed to ensure the readability and maintainability of custom developmentprograms and to provide a consistent and meaningful interface for the user on screens and report output.

    Naming conventions

    Naming conventions are the result of agreement among customer and implementation partner to use standardgeneric prefixes when assigning names to development objects, for example, function modules, programming

    elements, or variables. The system itself does not usually check that these naming conventions are adhered to.The responsibility for this lies with the individual developer.

    Please refer to the Naming conventions document for detailed information.

    Development Guidelines

    Key to the Rule column:

    X (mandatory rule) (rule is optional - recommendation as a way of improving quality)

    General Rules Mandatory

    All names (variables, programs, function modules, classes, and so on) in English X

    Use meaningful names (for example, use lv_material not lv_m)Wherever possible, use glossary terms (for example, lv_company_code notlv_bukrs)

    X

    Use underscores (_) to separate the different words in compound names X

    Write comments and documentation in the coding in English X

    Write comments in the coding as though you were explaining the program to acolleague

    X

    Use the pretty printer (if the pretty printer is not available, structure manually) X

    Use TODO to run syntax checks / CHECKMAN (if applicable, CHECKMAN normally

    not available in customer systems)

    X

    Run enhanced syntax checks (SLIN) X

    Store generally reusable program parts in function modules

    Program with reusability in mind

    Use a maximum of one statement per program line X

    Divide larger function modules into form routines

    Use modularization techniques to structure your programs, avoid spaghetti coding

    Do not overload coding with technical refinementsCRM: Avoid complex statements (the results quantity must be easily recognizable)

    Do not encapsulate if-statements to much

    Keep select statements as simple as possible (for example, do not useoverly complex joins)

    Page 3 of 20

  • 8/2/2019 ABAP Program Standards

    4/20

    Programming Standards

    Optimize only where it is useful or meaningful to do so

    Create types and data definitions only with a DDIC reference Central changes

    are possible (for example, field lengths) and it is better to use TYPE instead of LIKE(constant typing Basis recommendation)

    Use constants instead of literals X

    Define constants globally (multiple use, simple central modifications!) X

    Use TABLES statements only when absolutely necessaryIf you have to use TABLES statements, always use them globallyAllowed, for example, in function groups with database accessNot necessary for select statements of the SELECT INTO wa ENDSELECT type

    X

    Do not use data structures from TABLES statements directly

    Use internal tables without headersThis also applies, for example, to the transfer of internal tables to function modulesHeaders (internal tables as parameters of a function module are always createdwith headers within the function module) are also not allowed within the functionmoduleNote: Tables with headers are no longer supported in an ABAP-OO context

    X

    If sorted data is required, the tables in which the data is managed must always bestored in SORTED TABLESReason: Considerable improvement in performance when accessing data, becausebinary searches are possible There is also no need to sort using SORTED BYstatements

    Keep the number of global variables to a minimum Use local variables wherever

    possibleIn this context, the following applies for function modules:

    Define variables and structures globally only if several function modules needthem to transfer data or if they function as a memory aid!

    Define locally in the individual function modules any variables that are used byseveral function modules independently, but individually are of local importanceonly

    X

    Modules should consist of subprogram calls (PERFORM statements) only, meaningthat the coding should run only in the subprogramReason: Variables in modules are always global

    Use annotated coding as a temporary measure only and delete any commentary

    from the source text after an appropriate period of time has elapsed (for example,before the next release)Note: If you add any commentary to the coding, you should include the date,developer ID, and reason for the comment.

    Use any modules that are no longer required only in the short term and delete themafter an appropriate amount of time has elapsed

    Be aware of layer models:The different layers should be clearly separated from one another. Only specificinterfaces must be used to communicate between the layers.Example of a layer model: User Interface Layer Business Logic Layer DatabaseLayer

    ( There are detailed descriptions in CRM, for example)

    Never make changes to the database directly. Always use update modules that call

    the update task.

    X

    Function modules must always be used in read accesses (SELECT) to databases X

    Page 4 of 20

  • 8/2/2019 ABAP Program Standards

    5/20

    Programming Standards

    Benefits:

    Enables maintenance to be carried out centrally Buffering

    Never read function codes, screen numbers, or transaction codesReason: Leads to problems with generic functions and makes maintenance difficult

    If system variables (sy-repid, for example) are used as parameters, they shouldalways be stored in local variablesReason: System variables are reset when other programs or function modules arecalled, and could therefore be incorrect in the program that is called

    Do not work with the memory (import/export, set/get)

    Use your own function modules as a memory instead

    Avoid CALL DIALOG callsReason: A separate roll area is opened, and there is a danger that different rollareas could be using a different DB status

    Do not use macros! They are difficult to maintain and cannot be debugged

    Macros? What are they?!Use the application log to manage messages (warnings, errors, and so on) seethe reuse library

    Initialize new DDIC table fields only in exceptional cases, meaning when it isabsolutely necessary Leads to unnecessary type conversions

    Leave new fields with a ZERO value in case an initialization in accordance withthe data type is not explicitly necessary (time during upgrade, memory usage)

    Number fixed values consecutively or start with the letter A and work through thealphabetReason: Since the software is used worldwide, there is no point in trying to identifyfixed values by the first letter or their German or English names

    Work with includes as much as possible when you define tables.

    This means, first collect in an include all the parts that logically belong together, andthen use this include when you define the tablesThis enables recycling and makes modifications easier

    What happens when existing tables are added to an include?

    Reference data types not table fields (for example, TYPE MATNR not LIKE MARA-MATNR)

    Screens:Always define screen fields with a DDIC referenceNever use global variables as screen fieldsAlways define screen texts with a DDIC reference

    Do not modify text in the coding or use screen attributes to modify text

    Text is written and translated in one place Use complete text (in field labels and headings)

    Store automatically generated maintenance views (maintenance clusters) inseparate function groupsModifications to the flow logic of generated maintenance screens should take placeonly using the events designed for this purpose in the maintenance views(otherwise your modifications will be overwritten when the dialog is generated again.

    Separate function groups for read access to customizing objectsReason: Performance the maintenance function modules should not be loaded ina read access (the complete function group is always loaded when a functionmodule is accessed)

    Always deal with exceptions!If an exception has not been dealt with, the situation must be documented clearly!

    X

    Rules for Form Routines and Function Modules Rule

    Page 5 of 20

  • 8/2/2019 ABAP Program Standards

    6/20

    Programming Standards

    Use a generated header (document header) for a new formThis header must always be filled out fully (see documentation guidelines),the parameters must be described (see below), and all accesses to tables and data

    structures must be documented

    X

    Parameter Transfer

    Transfer parameters must always be typed (improved syntax check, better readability,better performance see Tips&Tricks in transaction SE30)

    Transfer parameters that are not changed must always declare with USING and BY VALUE in subprograms (FORMS);

    Exception: Do not pass tables By VALUE (memory consumption) always declare as IMPORTING parameters in function modules

    All transfer parameters must be documented in the header and be classified asimport / export parameters

    Whenever possible, avoid using global variables for hidden parameter transfers! Ifglobal variables are used, they must be documented in the header and classified(READ / WRITE)

    Export parameters must be initialized at the start of the subprogram

    X

    Store part-functions in their own form routinesOmit form routines to optimize performance only in cases where mass processing is themain consideration, otherwise the rule is - maintainability before runtime optimization

    Avoid calling external form routines - call function modules instead whenever possible

    Before the release of the task and transport request, the following steps are mandatory.

    Mandatory Steps for completion of Coding Tools to be used

    Use of code review checklist Excel Doc

    Extended Program Check/ Extended Syntax Check SLIN Transaction

    Code Inspector SCID

    Runtime Analysis SE30

    SQL Trace ST05

    The runtime Analysis and SQL trace are to be done wherever relevant.

    Documentation within the CodeThe programs should have a header as defined in the templateA comment box should precede the subroutine describing in brief the functionalityInclude full line comments to explain blocks of code.

    Program HeaderAt the top of programs, function modules a header has to be included.

    Page 6 of 20

  • 8/2/2019 ABAP Program Standards

    7/20

    Programming Standards

    *---------------------------------------------------------------***************************************************************** ABAP Name: Zxxxxxxxxxxxxxxx* Created by: ________ * Created on: mm/dd/yyyy.

    * Version: n.n*---------------------------------------------------------------* Comments: purpose, use, design, structure, testing hints, etc***---------------------------------------------------------------* Modification Log:* Date Programmer Correction Description**---------------------------------------------------------------

    A header documentation program can be created for example ZREPORTHDR by the team leads. The abovecode to be copied into the same. You can insert this header into the ABAP using the Insert Statement function

    found on menu path Edit Pattern.

    NOTE: Function local interface documentation generated by the function builder. Do not change.

    SubroutinesA comment box must precede the subroutine. The comment box should contain the name of the subroutine anda short description of its function (what it is doing, not how it is doing it).

    Example:

    *---------------------------------------------------------------** Form GET_MATERIAL_DETAILS **---------------------------------------------------------------** This form is to read mara and get the details of the ** material. **---------------------------------------------------------------*FORM GET_MATERIAL_DETAILS USING LV_MATNR.

    Events

    Events should have a defining header to separate them from the processing logic.

    Example********************************************************************* START-OF-SELECTION PROCESSING *********************************************************************

    Modules*----------------------------------------------------------** MODULE SET_PFSTATUS OUTPUT **----------------------------------------------------------** Set GUI Status based on whether the transaction is a ** CREATE< CHANGE or DISPLAY *

    * **----------------------------------------------------------*

    Module Pool ProgramsModule pools (also known as Dialog Modules) are associated with transaction screen flow. The programsconsist of data definitions, MODULE / ENDMODULE coding blocks, and subroutines. These program elementsmay be found directly in the program or, using the traditional approach, as INCLUDE programs within themodule pool program. The Header documentation and Include naming convention are to be followed.

    Function Pool (Group) ProgramsFunction groups programs are containers for function modules and are maintained by the function builder. LikeModule Pool programs, they only contain INCLUDE statements. They should not be changed manually.

    Page 7 of 20

  • 8/2/2019 ABAP Program Standards

    8/20

    Programming Standards

    Subroutine Pool ProgramsSubroutine pool programs are collections of FORM routines called from external programs. The general formnaming conventions and documentations are to be followed.

    Class Pool DocumentationClass pool documentation is maintained in the Class Builder. For custom classes, the documentation shouldhave the following format.

    *----------------------------------------------------------*CL ZCL_nnnnnnnnnnnnnnnnnOwnership:Created by: ________ Created on: mm/dd/yyyy.Version: n.n*----------------------------------------------------------*

    Modification Log:Date Programmer Correction Description

    Functionality:Description of class

    Relationships:Relationships with other classes

    Example:Example showing use of CLASS

    Notes:Special considerations

    Further Information:Where to find more informaiton

    *----------------------------------------------------------*

    Interface Pool DocumentationInterface pool documentation is maintained in the Class Builder. For custom interfaces, the documentationshould have the following format.

    *----------------------------------------------------------*IF ZIF_nnnnnnnnnnnnnnnnnOwnership:

    Created by: ________ Created on: mm/dd/yyyy.Version: n.n

    *----------------------------------------------------------*Modification Log:

    Date Programmer Correction Description

    Functionality:Description of class

    Relationships:Relationships with other classes

    Example:Example showing use of CLASS

    Notes:Special considerations

    Further Information:Where to find more informaiton

    *----------------------------------------------------------*

    Changes and EnhancementsIf a modification is made to an existing custom ABAP program, an entry should be made in the modification logwith the date, programmers initials, correction number, change management number (?) and brief description.Also, in the program code, a comment should be added to the effected lines indicating the correction number.

    Page 8 of 20

  • 8/2/2019 ABAP Program Standards

    9/20

    Programming Standards

    Example:IF SY-SUBRC NE 0. DevK9000045

    Exit. DevK9000045ENDIF. DevK9000045

    User DocumentationUser or use documentation should be maintained using the ABAP documentation feature through the menu

    toolbar Goto Documentation Change. You will then be presented with SAPs standard programdocumentation template with paragraph headers for:

    TITLE: copied from the attributes screen title field.

    PURPOSE: detailed User description of the programs purpose. Include any precautions the usershould be aware of resulting from the execution of this program.

    INTEGRATION: integration points with other applications or partner systems

    PREREQUISITES: describe any prerequisite activities.

    FEATURES:

    Selection: - advice on selection screen fields Standard Variants: - pre-defined variants set up for general reporting needs

    Output: - content of the print list

    ACTIVITIES: - follow-on activities. As an example, instructions for interactive reporting

    EXAMPLES: - processing hints, helpful information on running the program.

    This documentation is then available to the user at execution time through the same menu pathdescribed above or though Program Documentation icon which is automatically added to the reportselection screen Application Toolbar in the GUI interface.

    Text ElementsEach ABAP should have associated text elements and constants from the source code placed within the TextElements section of the ABAP Editor

    Titles and Headings

    The heading should always be completed in as much detail as possible. Use of standard headings is preferredas they can be easily made multilingual. The alternative is coded headings, which require further coding for eachlanguage supported. Note: Any data entered here will not show up in the report header if the program uses theNo Standard Page Heading phrase and codes a custom header.

    Selection Texts

    All system SELECT-OPTIONS and PARAMETERS are limited to 8 characters and as a consequence shouldalways have selection texts set to improve user understanding.

    Text-Symbols

    Literal text that is printed on the report can be handled two ways. One way is to hard code the literal in the code

    and give the option of maintaining Text Elements for multilingual clients.

    Example:WRITE: / Grand Total:(001).

    The advantages of this method are readability and only the text element needs to be maintained for multilingualclients.

    As a standard, use the following example.

    Example:TEXT-001 defined as Grand Total:WRITE: / TEXT-001.

    The advantage of this method is ease of maintainability if TEXT-001 is coded several times in the program andneeds to be changed.

    Page 9 of 20

  • 8/2/2019 ABAP Program Standards

    10/20

    Programming Standards

    Message Classes

    Messages should be used in all dialog processing and in conveying errors or processing status in an online

    program execution to the user.

    Changing SAP Code

    Changes to SAP programs are usually recommended by SAP via SAP OSS Notes to solve specific customerissues. Although, the customer may also make the determination after reviewing all options, that changes toSAP programs are needed.

    Whatever the source, there must be tight controls when making changes to SAP code and such changes mustfirst be approved by ABB SAS team.

    It is critical that any code changes to the SAP code are clearly documented. The standard is to create a sectionin the Program Header (see below), detailing the date the changes were made, who made the changes, theRepair number, the issue number the change relates to (found in the Change Management Logs), the OSS NoteNumber and a short description.

    Example*---------------------------------------------------------------***************************************************************** Modification Log:* Date Programmer Correction Description***---------------------------------------------------------------

    The code changes made in the SAP Standard Programs must follow the documentation standards used bySAP, with the addition of the correction number in the comments.

    Example*>> BEGIN OF INSERT OSS 1234567 DEVK900012

    IF SY-SUBRC 0.PERFORM CHECK_RFC.

    ENDIF.*

  • 8/2/2019 ABAP Program Standards

    11/20

    Programming Standards

    Database UpdatesUpdate modules should be used for database updates. They should be bundled in proper LUW for transactionalintegrity. Z tables should be updated using update function modules.

    Database Operations (SQL)There are several ways of using select statements. The following are suggested ways of using SQL statementsfor optimized performance.

    Select Statement

    Do not use SELECT inside a LOOP.The disadvantage of using SQL statement in a loop is that select statement is executed for every record in theouter table.

    Select vs. Select*Using Select field1 field2 .. Instead of Select * is significantly faster if the table contains a large number offieldsExample:Recommended:SELECT FIELD1 FIELD2 FIELD3 FROM TAB1

    INTO TABLE IT_TAB1WHERE FIELD1 IN O_FIELD1.

    Not Recommended:

    SELECT * FROM TAB1 INTO TABLE IT_TAB1WHERE FIELD1 IN O_FIELD1.

    Recommendation:

    1. Use Select :2. Table consists of a large number of fields3. Data retrieval is limited to a relatively small number of fields compared to overall number of fields.

    Hence, less memory usage and network load.4. Use of Select * should be used on an exception basis ONLY.

    Select into vs. Select into corresponding fieldsExample:Recommended:SELECT FIELD1 FIELD2 FIELD3 FROM TAB1

    INTO TABLE IT_TAB1 WHERE FIELD1 IN O_FIELD1.

    Not Recommended:

    SELECT FIELD1 FIELD2 FIELD3 FROM TAB1INTO CORRESPONDING FIELD OF TABLE IT_TAB1WHERE FIELD1 IN O_FIELD1.

    Existence checkAvoid using Select COUNT (*) to verify the existence of records in a table as the COUNT function scans throughall records within a table.Sort during Select vs. ABAP sortThere are two ways of sorting application data. One is sorting on the database server and the other is sortingon the application server.Recommended:Example: Sorting data after select statementSELECT FIELD1 FIELD2 FIELD3 FROM TAB1

    INTO TABLE 1T_TAB1 WHERE FIELD1 = 'X'.

    SORT IT_TAB1 BY FIELD1.

    Page 11 of 20

  • 8/2/2019 ABAP Program Standards

    12/20

    Programming Standards

    Not Recommended:Example: Sorting data in the select statementSELECT FIELD1 FIELD2 FIELD3 FROM TAB1

    INTO TABLE IT_TAB1 WHERE FIELD1 = 'X'ORDER BY DISPO MATNR.

    Select distinctThe DISTINCT addition to the SELECT statement allows you to remove duplicates from a set of results during aSELECT.SELECT DISTINCT FIELD2 FROM TAB1

    INTO TABLE IT_TAB1WHERE FIELD1 = 'ABC'.

    Disadvantages:5. Requires sorting on database server and adversely affects overall system performance if no index can be

    used6. When using DISTINCT the database is always accessed directly by passing the SAP buffer

    Alternative approach:SELECT FIELD2 FROM TAB1

    INTO TABLE IT_TAB1WHERE FIELD = 'ABC'.

    SORT IT_TAB1 BY FIELD2.

    DELETE ADJACENT DUPLICATES FROM IT_TAB1 COMPARING FIELD2.

    Array updatesAll Database manipulations in SAP (UPDATE, INSERT, DELETE) can be executed one record at a time orthrough an 'Array' operation. The recommended mode is the array operation

    Example:Not recommended:LOOP AT IT_TAB1.UPDATE ZTAB1 SET FIELD1 = IT_TAB1-FIELD.

    WHERE FIELD2 = IT_TAB1-FIELD2.ENDLOOP.

    Recommended:LOOP AT IT_TAB1.

    ENDLOOPUPDATE ZTAB1 FROM TABLE IT_TAB1.

    After the execution of the array update, the following system fields are populated:7. SY-SUBRC

    Contains 0 if all updates were successfully executed8. SY-DBCNT

    Contains the number of successfully updated records

    Open SQL VS. Native SQLDevelopers are not supposed to use native SQL.

    JoinSince joins are executed at the database level they limit network traffic and increase efficiency. A disadvantageof join is that it bypasses SAPs buffer at application server level.Example: Use of INNER JOINSELECT T1~AUART T2~MATNR INTO TABLE IT_ORDER

    FROM VBAK AS T1 INNER JOIN VBAP AS T2ON T1~VBELN = T2~VBELN WHERE VBELN IN O_VBELN.

    Page 12 of 20

  • 8/2/2019 ABAP Program Standards

    13/20

    Programming Standards

    The initial design of the SQL statement with INNER JOINs should start with the smaller table as a general rule.However there can be some exceptions to this, based on the business data pattern and filter conditions:

    The starting table (Primary table in the join) should have specific where clause on the primary key fieldsor a clean secondary index. This will also be taken care of by the cost based optimizer in most of thecases

    The starting table (Primary table in the join) should be the one with maximum filter criteria. This reduces

    the database I/O and disk reads. However a comparison for response time and estimated cost issuggested in this case.

    Use LEFT OUTER JOINs with caution since they can impact performance. A LEFT OUTER JOIN produces a

    resulting set containing all data records from the outer table, regardless of whether matching records exist in the

    inner table. If there are no matching data records in the inner table, NULL values are returned for the fields in

    the inner table.

    An alternative is to define JOINs as views in the database. Views are statically and globally defined in the ABAP

    Dictionary and can be used by all ABAP programs. Views are implemented in the ABAP Dictionary as INNER

    JOINs. The fields that are common to both tables are transferred only once from the database server to the

    application server. Views are more efficient than implementing ABAP JOINs since they utilize the buffering

    advantages offered by the SAP system.

    Nested selects should be avoided at all costs as the connection to the database stays open for each record in

    the outer select loop.

    IndexesThe index search is very fast if you check all index fields for equality and combine them with the AND operator.

    Avoid using the NOT operator in the WHERE clause, since this will prevent the database optimizer from usingthe index. The database system supports only SQL statements that are defined in positive terms for example,

    EQ and LIKE (not NE and NOT LIKE). If possible, invert the logical expression instead.The database optimizer halts when it sees an inner OR in an expression of an SQL statement. Try toreformulate such conditions into forms relevant to the index, such as an IN condition. For example, you shouldavoid the following SELECT statement, which has an inner OR:

    Avoid using the NOT operator in the WHERE clause, since this will prevent the database optimizer from usingthe index. The database system supports only SQL statements that are defined in positive terms for example,EQ and LIKE (not NE and NOT LIKE). If possible, invert the logical expression instead. The database optimizerhalts when it sees an inner OR in an expression of an SQL statement. Try to reformulate such conditions intoforms relevant to the index, such as an IN condition. For example, you should avoid the following SELECTstatement, which has an inner OR:

    SubqueriesA subquery is a SELECT command within another SELECT, specified in the WHERE condition, that checkswhether data from a database table or view meets certain conditions. In addition, subqueries can be used inUPDATE and DELETE statements as well.Advantages:9. Complex queries can be efficiently implemented

    Disadvantages:10. When Subqueries are used the query is executed at the database level bypassing SAPs internal database

    buffer

    Restrictions:Select single can't be used together with subqueries

    FOR ALL ENTRIES (FAEI)

    Page 13 of 20

  • 8/2/2019 ABAP Program Standards

    14/20

    Programming Standards

    This version of the SELECT statement was the only way to join tables until SAP release 3.0E. It isrecommended that the SQL JOIN be used. However, this is an alternate method of joining tables that may beused in some circumstances. Remember, SQL JOIN doesnt utilize the SAP internal database buffer.

    Prerequisites:1) The driver table cannot be empty. This would cause one full table scan.2) In general, keep the driver table as small and unique (in regards to the fields that would be needed forreferencing in the FAEI) as possible. If duplicate entries are not deleted, identical data is read unnecessarilyfrom the database.3) If FAEI is used, the selected field list must be a superset of all the key fields of the database tables used inSQL. This is absolutely required to avoid data loss since the DB interface in R/3 returns unique sets of the resultset to the application program. Failing to ensure this may cause problems when you want to get all records froma database table that match a certain condition.4) Avoid using FAEI on a small DB table (like configuration tables). This could potentially cause full table scansfor each FAEI packet. Even if it does index range scan, it is better to get data from the small DB tables byindividual SELECT without the use of FAE.

    5) Always use FAEI in conjunction with a DB index otherwise it would cause multiple full table scans (one tablescan for each FAEI packet).6) The first field(s) of the DB index should refer to the fields of the FAEI driver table in the SQL WHERE clause.Do not leave gaps between index fields in the WHERE clause. Inefficient index access will impact every FAEIpackets.

    7) FAEI works best when retrieving a small percentage of data from a Database table. When a large percentageof data is needed, consider getting data out of the DB table without FAEI implementation, and then do additionalfiltration in your application.

    Accessing data in Packages

    Consider using PACKAGE SIZE in SELECT statement when size of resultant itab is significant in size (e.g.when row width and volume of rows is large). Instead of retrieving all data in one select statement a select loop

    is executed multiple times providing a data package for each loop.

    Do not use APPENDING TABLE with PACKAGE SIZE.

    The use of PACKAGE SIZE is not recommended if FOR ALL ENTRIES is being used because FAEI defines itsown package size

    Example:

    SELECT FIELD1 FIELD2 FIELD3 FROM TAB1 INTO TABLE IT_TAB1PACKAGE SIZE 10000.

    LOOP AT IT_TAB1..

    ENDLOOP.ENDSELECT.

    In this example 10000 lines are added to the internal table IT_TAB1 during each select loop.

    SAP Index tablesReview and evaluate the use of alternate index tables before creating indexes on any existing SAP transactiontables.

    Some examples of index tables:VAKGU Sales Index: Quotation ValidityVAKPA Sales Index: Orders by Partner FunctionVAPMA Sales Index: Order Items by MaterialVBOX SD Document: Billing Document: Rebate IndexVEPVG Delivery Due IndexVETVG Delivery Due Index for Stock Transfer

    Page 14 of 20

  • 8/2/2019 ABAP Program Standards

    15/20

    Programming Standards

    VKDFS SD Index: Billing Initiator VLKPA SD Index: Deliveries by Partner FunctionsVLPMA SD Index: Delivery Items by Material

    VRKPA Sales Index: Bills by Partner FunctionsVRPMA SD Index: Billing Items per MaterialVTRDI Shipment Planning IndexEKKI Purchasing Condition IndexEKUB Index for Stock Transport Orders for MaterialBSAD Accounting: Secondary Index for Customers (Cleared ItemsBSAK Accounting: Secondary Index for Vendors (Cleared Items)BSAS Accounting: Secondary Index for G/L Accounts (Cleared ItBSIA Archive Index for FI Documents (Outdated! See ARCH_IDX)BSID Accounting: Secondary Index for CustomersBSIK Accounting: Secondary Index for VendorsBSIM Secondary Index, Documents for MaterialBSIP Index for Vendor Validation of Double Documents

    BSIS Accounting: Secondary Index for G/L AccountsBSIW Index table for customer bills of exchange usedBSIX Index table for customer bills of exchange used

    Usage of Internal table typesUse the following guidelines when deciding between the different table types11. Type STANDARD should be used as default type12. Type HASHED if the internal table contains a large number of records and your program requires a large

    number of primary (unique) key accesses13. Avoid using SORTED tables since the performance gain compared to a standard table is minimal, and it

    includes the risk that the sort sequence is corrupted by using INSERT, APPEND or MODIFY with Indexoption

    Defining Internal TablesThe following is the recommended way of defining internal tables.

    TYPES: BEGIN OF TYPE_MAT,MATNR LIKE MARA-MATNR,

    WERKS LIKE MARC-WERKS,DISPO LIKE MARC-DISPO,

    END OF TYPE_MAT.

    DATA: IT_MAT TYPE STANDARD TABLE OF TYPE_MAT.

    Working with Internal TablesModifying Components of an Internal Table

    With the MODIFY variant MODIFY itab ... TRANSPORTING f1 f2 ... WHERE condition, the task of updating aset of lines of an internal table can be accelerated considerably. Especially if tables embedded in the lines canbe ignored while updating, the performance advantage is considerable.

    Example: Table TAB is filled with 5000 entries of 500 bytes each. Actually, only the 8 bytes of the componentDATE are modified.

    Modifying all components through loop processingMass modify for internal table should be preferred over modification inside a loop

    Appending an internal table to another internal tableExample:

    Page 15 of 20

  • 8/2/2019 ABAP Program Standards

    16/20

    Programming Standards

    Table TAB_SRC and TAB_DEST are both filled with certain number of entries. TAB_SRC can be appended line by line toTAB_DEST but recommended way is mass append.Not recommended:Appending through loop processing

    LOOP AT TAB_SRC.APPEND TAB_SRC TO TAB_DEST.

    ENDLOOP.Recommended:Appending through mass appendAPPEND LINES OF TAB_SRC TO TAB_DEST.

    Delete duplicates from a sorted internal tableTo delete duplicates from an internal table first it has to be sorted and then it has to be deleted as below.DELETE ADJACENT DUPLICATES FROM IT_TAB1 COMPARING FIELD1.

    Delete a set of lines specified with a where conditionExample:Table TAB_DEST is filled with 1000 entries of 500 bytes each, 250 of which match the WHERE condition

    Not Recommended:Delete using loop processingLOOP AT IT_TAB1 WHERE FIELD1 = VAL1.

    DELETE IT_TAB1.ENDLOOP.

    Recommended:Delete using the WHERE clauseLet the kernel do the work

    DELETE IT_TAB1 WHERE FIELD1 = VAL1.

    Delete using conditional loop processingLOOP AT IT_TAB1

    IF CONDITION = TRUE.DELETE IT_TAB1.

    ENDIF.ENDLOOP.

    Delete using the WHERE clause

    Let the kernel do the work

    LOOP AT IT_TAB1IF CONDITION = TRUE.

    S_TAB1-DEL_FLAG = X.MODIFY IT_TAB1 FROM S_TAB1 TRANSPORTING DEL_FLAG.

    ENDIF.ENDLOOP.DELETE IT_TAB1 WHERE DEL_FLAG = X.

    Determining an empty internal table

    Example:Not Recommended:DESCRIBE TABLE TAB1 LINES L1.IF L1 = 0.

    *Empty internal tableENDIF.

    Recommended:IF TAB1[ ] is initial.

    * Empty internal tableENDIF.

    Reading from an Internal TableFor reading the table the preferred method is using index. If it is not possible then binary search may be used.

    Page 16 of 20

  • 8/2/2019 ABAP Program Standards

    17/20

    Programming Standards

    Key SearchREAD TABLE TAB ASSIGNING WITH KEY = .

    Key/Binary SearchREAD TABLE TAB ASSIGNING WITH KEY = BINARY SEARCH.

    Search with Table IndexREAD TABLE TAB ASSIGNING INDEX .

    The READ using the Table Index search is the fastest and the Key Search is the slowest.

    Listed below are some of the common cases in which the READ statement is used during coding of programs.The best approach will be demonstrated based on the situation.

    Examples:Table IT_TAB1 is filled with n1 entries.Table IT_TAB2 is filled with n2 entries.

    Table TAB1 and TAB2 are assumed to be sorted by K in ascending orderNot Recommended:

    Join two internal tables using key searchLOOP AT IT_TAB1.

    READ TABLE IT_TAB2 WITH KEY K = IT_TAB1-KCHECK SY-SUBRC = 0.ENDLOOP.

    Recommended:Join two internal tables using key/binary searchNote: In this example, IT_TAB2 is sorted by K in ascending order.

    LOOP AT IT_TAB1.READ TABLE IT_TAB2 WITH KEY K = IT_TAB1-K BINARY SEARCH.

    CHECK SY-SUBRC = 0.ENDLOOP.

    Join two internal tables using parallel cursorNote: In this example, IT_TAB1 and IT_TAB2 are sorted by K in ascending order.Recommended:I2 = 1.LOOP AT IT_TAB1.

    READ TABLE IT_TAB2 INDEX I2.CHECK SY-SUBRC = 0.

    IF IT_TAB2-K = IT_TAB1-K.I2 = I2 + 1.

    ENDIF.ENDLOOP.

    Read (1:N case) From Internal TableExamples:Table IT_TAB1 is filled with n1 entries.Table IT_TAB2 is filled with n2 entries.

    Not Recommended:Join two internal tables using nested loops with WHERE conditionTable IT_TAB1 and IT_TAB2 are assumed to be sorted by K in ascending order

    LOOP AT IT_TAB1.LOOP AT IT_TAB2 WHERE K = IT_TAB1-K.ENDLOOP.

    ENDLOOP.

    Recommended:Join two internal tables using parallel cursor (BINARY SEARCH)Note: In this example, IT_TAB2 is sorted by K in ascending order.

    LOOP AT IT_TAB1.CLEAR V_TABIX.READ TABLE IT_TAB2 WITH KEY K = IT_TAB1-K BINARY SEARCH.

    CHECK SY-SUBRC = 0.V_TABIX = SY-TABIX.LOOP AT IT_TAB2 FROM V_TABIX.

    Page 17 of 20

  • 8/2/2019 ABAP Program Standards

    18/20

    Programming Standards

    IF IT_TAB2-K IT_TAB1-K.EXIT.

    ENDIF.ENDLOOP.

    ENDLOOP.

    Join two internal tables using parallel cursor (ASSIGNING)Note: In this example, IT_TAB1 and IT_TAB2 are sorted by K in ascending order.

    I2 = 1.LOOP AT IT_TAB1 ASSIGNING .

    LOOP AT IT_TAB2 ASSIGNING FROM I2.IF -K -K.

    I2 = SY-TABIX.EXIT.

    ENDIF.ENDLOOP.

    ENDLOOP.

    Function Module Exception Handling

    For SAP function modules or generic custom function modules we MUST handle the messaging ourselves sincewe don't have detailed messages in the functions. In order for the generic syntax to work below the functionmust make use of the Message...Raisingformat so that the SY variables are properly set.

    After a call to a function, the developers are routinely using the following default as inserted by the editor.

    Incorrect:

    IF sy-subrc 0.

    MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgnoWITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.

    ENDIF.

    This is not allowed unless the Message...Raising format is used consistently throughout thefunction.

    The following is the recommended way of handling message.

    Correct:

    CALL FUNCTION 'Z_FUNCTION_1'EXPORTING

    p_val1 = lv_val1p_val2 = lv_val2

    TABLESt_tab1 = lt_tab1t_tab2 = lt_tab2

    EXCEPTIONSError1 = 1Error2 = 2OTHERS = 3.

    CASE sy-subrc.WHEN 1.MESSAGE e100 WITH 'Error1'.

    WHEN 2.MESSAGE e101 WITH 'Error2'.

    WHEN 3.MESSAGE e102 WITH 'Error3.

    ENDCASE.

    Page 18 of 20

  • 8/2/2019 ABAP Program Standards

    19/20

    Programming Standards

    Reusing Existing Data Elements/Domains vs. Creating New OnesBelow are general rules on when to create a custom data element/domain and when to reuse an existing SAPdata element/domain.

    If SAP delivered fields are included in custom tables, reuse the existing data elements/domains. When creating a custom field, make the name meaningful from a business standpoint dont use generic

    names such as TEXT40, CHAR1 for data elements. However, if the values are constrained generically (e.g.yes/no field or text only field) then associate the data element to an existing generic domain such asCHAR1, TEXT40, etc.

    If custom fields refer to check tables or require a set of limited default values, create a custom domain. Do not modify existing SAP data elements/domains as this is considered a modification to SAP. When creating structures, you are to use existing data elements/domains if possible. If the element/domain

    does not exist, then use the proper naming convention for creating custom elements/domains.

    Adding Customer Fields to SAP Delivered TablesAppend structures structures must be used when adding custom fields to SAP delivered tables.

    Data Elements in the Data DictionaryEach new custom Data Elements each Data Element will require

    Meaningful descriptionThis description is displayed on field level within custom tables

    Meaningful labels (Short, Medium, Long, Header)This description is displayed whenever a data dictionary field is used inside SAP screens

    Meaningful long text documentation ('Documentation' button on application toolbar)this description is displayed as field level on-line help.

    Program Layout

    Source Code should be formatted using pretty printer. The keywords must be in upper case, rest of the sourcecode should be in lower case. The required settings should be made in the editor for this purpose.

    Parameters and Selection Screen Fields

    Hard coding values must be avoided. For data that determines the data selection, program logic or theoutput processing, define a parameter or selection screen field and pass values through the parameters.Parameter or selection field can be used to pass values for selection from the database or to specify the

    input and output file names. Avoid the use of DEFAULT values for parameters/selection screen fields. Create variants, where possible,

    and have the user community use the variant to default values to the screen.Exceptions from this rule are non-business related parameters i.e. Logical File Names, Call transactionMode, packet size setting.

    Avoid the use of OBLIGATORY. The use of required fields on the selection screens can cause problemsfor variant definition. Any validation of select-options or parameters should occur in the AT SELECTION-SCREEN event.

    Local vs. Global VariablesA clear demarcation has to be made between variables that are used globally and locally. Variables used locallyshould be defined as local variables and variables used globally should be defined as global variables.

    Page 19 of 20

  • 8/2/2019 ABAP Program Standards

    20/20

    Programming Standards

    Modularization

    Subroutines and Function ModulesSubroutines should be used to make code modular. This also helps is code readability and maintenance.

    Blocks of code that is used more than once in a program should be organized in subroutines. Separatesubroutines should be defined for separate processes.

    In case a block of code can be used by multiple programs it is better to place it in a function module.

    Function GroupsFunction Groups must be used to store Function Modules, which are commonly called within the same logicalunit of work. All Functions within the same Function Group share a global memory area. When a program callsa Function Module, all the Function Modules within that group are loaded into memory allowing the Function

    Modules to share global data and to reduce system overhead. However, if a Function Module is commonlycalled individually, it should be the sole member of a Function Group. Dynamically called Function Modulesmust be separate from other Function Modules in their own Function Group.

    If Function Modules are being called IN UPDATE TASK and are using internal tables that are defined as GlobalData, the global internal table will need to be cleared each time the function module is being executed.Otherwise the internal table records are still available from the last function module execution and could causee.g. Duplicate Key Update Task failures.

    Authorization Check

    All custom development objects need to have an authorization object to ensure the security of the data that issaved or displayed.The authorization object is ZPRCHK_NEW. The authorization fields available for the check are

    TCD Transaction CodePRCTR Profit CenterSPART DivisionWERKS PlantVKORG Sales OrganizationEKORG Purchasing Organization

    Country Specific development

    The country specific developments must run just for the country specific processes. This is ensured by havingthe check for country in each of the developments. A function module will return the country code. The processlogic should check for the particular country and ensured that the development works for only for the necessary

    country. The function module is ZCAGL_COMPANYCODE. The input to the function module iscompany code, profit centre, plant or division. The output provides the unique country code for

    the respective input.

    Page 20 of 20