ZABAP Coding Standards V2 0

19
ABAP Coding Standards Reference Guide August 2010

Transcript of ZABAP Coding Standards V2 0

  • ABAP Coding Standards

    Reference GuideAugust 2010

  • Reference Guide | 1ABAP Coding Standards

    CONFIDENTIAL ABAP Coding Standards - Reference Guide. Vers. 2.0

    Copyright 2010. CodeExcellence Inc. All Rights Reserved

    INTrODuCTION This document provides a quick reference to ABAP coding standards and expectations for new SAP development. The standards represent a minimum requirement and are intended to be an adjunct to other commonly accepted best practices in the industry. The corporate coding rules, which are described in the document, can be monitored using the HAWKEYE Monitor tool.

    A key element of the coding standards and application governance methodology is the application of an automatic code review process using HAWKEYE. The Hawkeye system continually scans code, generates real time reports, and delivers alerts to management. In addition, developers can use the APOD tool. It helps ABAP programmers ensure their code is consistent with corporate expectations, quickly and efficiently.

  • Reference Guide | 2ABAP Coding Standards

    CONFIDENTIAL ABAP Coding Standards - Reference Guide. Vers. 2.0

    Copyright 2010. CodeExcellence Inc. All Rights Reserved

    ACCESS CONDITION WITHOuT ALL KEYS

    This rule covers both, SELECTs from database tables and READs from internal tables. Single rows in internal tables are accessed with a READ TABLE statement. All READs access the internal table by numeric index or with an internal table key. For READs with an incomplete or incorrect key there may be mulitple rows that satisfy the partial criteria. In this case the READ statement returns the first matching row. This may not match the

    expected result.

    Select Single should provide all fields of the Primary Key. The purpose of a select single

    is to retrieve a single unique row based on the unique primary key fields(s). Without all

    key fields specified, there may be multiple rows that satisfy the partial key criteria resulting

    in any one of the rows being returned. Therefore, the specific record expected may not

    be the one returned.

    ACCESSING ABAP MEMOrY WITHOuT ID

    Programs should always reference ABAP Memory by a unique ID. Referencing Memory generically can have impact on other applications using ABAP memory i.e. FREE MEMORY without an ID would wipe out all ABAP memory which could affect other programs that are counting on data in memory.

    ALV LIST VIEWEr Use ABAP List Viewer instead of Classic Lists. WRITE statements and classic report writing techniques are obsolete and should be replaced with ALV programming using the SAP List Viewer Object model. Complete ABAP OO programming is supported using SALV that delivers user flexibility for output format, feature rich programming, and end

    user capabilities without the need for additional programming. The area of report writing has gone through several progressions. As a programmer you will encounter all flavours

    of report programming as listed below.

    Classic List reporting using Write statements

    The first introduction of ALV with the REUSE* functions

    This was then replaced with the Class based ALV using CL_GUI_ALV_GRID

    And now a complete delivery of the ALV object model called SALV.

    All new report programming should use SALV* classes

    AMBIGuOuS FIELD NAME Avoid using field names that are the same as pre-defined SAP TYPES (N, I, F, D, etc) or operators.

    ArITHMETIC OPErATOrS INSTEAD OF WOrDS

    Use operators (+, -, *, /, =) rather than the obsolete words ADD, SUBTRACT, MULTIPLY,

    DIVIDE, MOVE.

    ASSIGNMENT HAS NO EFFECT Avoid assigning variables to themselves. There is no effect from this practice.

    BrEAK-POINT STATEMENT DETECTED

    All break-point statements must be removed prior to production. This could potentially

    stop production and provide back door access (I.e. debugger) into the code and

    confidential data.

  • Reference Guide | 3ABAP Coding Standards

    CONFIDENTIAL ABAP Coding Standards - Reference Guide. Vers. 2.0

    Copyright 2010. CodeExcellence Inc. All Rights Reserved

    BuFFEr INVALIDATED Tables buffered in the SAP table buffer should be changed as seldom as possible. In certain cases, local changes of a few records in a table can cause invalidation of the table in the buffer in other application servers. This will result in entries no longer being current in the buffer and will therefore have to be imported again from the database. Avoid any of the following scenarios that will invalidate the buffer:

    UPDATE/DELETE with a WHERE on single-record-buffered table.

    UPDATE/DELETE dbtab, UPDATE/DELETE dbtab FROM WA and UPDATE/DELETE

    dbtab FROM ITAB each invalidate only the specified records

    UPDATE/DELETE with a WHERE invalidates the entire table in the buffer.

    UPDATE/DELETE with a WHERE on generically buffered table and generic key not

    fully specified.

    UPDATE/DELETE with a WHERE, and the generic key in the WHERE condition is not

    fully specified, all the generic areas of the buffer are invalidated.

    INSERT/UPDATE/MODIFY/DELETE on completely buffered table.

    Each change of a completely buffered table invalidates the table in the buffers of the other application servers of the system. If the parameter "Only 'buffering switched on' " is set in the check, accesses to tables that allow the option 'buffering' in their technical properties, but have 'switched off' set, are not checked.

    BuFFErED TABLE IN A JOIN Avoid the use of Buffered Tables in a Join. This will cause bypass of the buffer.

    BuFFErED TABLE IN SELECT WITH SuBQuErY

    Avoid the use of buffered tables in a sub query to avoid bypassing the buffer.

    BYTE & CHArACTEr STrINGS Use the variable length statement STRING and XSTRING when declaring character and byte data variables. It provides better use of memory than fixed length text statements

    TYPE C and TYPE X.

    CALL TO EDITOr All EDITOR calls must be removed prior to production.

    CASE VErSuS IF Use the CASE statement rather than IF/ELSEIF/ENDIF construct when there are multiple = conditions. If there is only one condition, then the IF/ELSE/ENDIF statement is a good

    choice.

    CASE WHEN FIrST STATEMENT WHEN must be the first statement after a CASE statement.

    CASE WITHOuT WHEN OTHErS Case Statement requires a When Others clause. Any condition that is not met will have a fallout path. In the When Others, always provide an action or a generic message so that the program can announce that an unexpected situation has been encountered.

    CATCH - PrOCESSING MISSING Processing section inside the CATCH ENDCATCH block is empty. Exceptions must be explicitly handled within the CATCH ENDCATCH block. Add the required exception

    processing between CATCH and ENDCATCH

  • Reference Guide | 4ABAP Coding Standards

    CONFIDENTIAL ABAP Coding Standards - Reference Guide. Vers. 2.0

    Copyright 2010. CodeExcellence Inc. All Rights Reserved

    CLIENT SPECIFIED LIMITED TO SYSTEM TOOLS

    In Multi-Client production systems, regular ABAP application programs should never

    select data across clients with the CLIENT SPECIFIED option since theres a risk with

    mixing data across clients / companies. Standard SAP always stays within a client for

    regular application data and therefore custom code should follow the same rule. The use of CLIENT SPECIFIED should be limited to system tools.

    CLIENT SPECIFIED TABLE FIrST FIELD

    This is a Data Dictionary Requirement that Client Specified Tables MUST have the first

    field of the table defined as CLIENT (MANDT).

    CODING BLOCK EMPTY Do not create empty coding blocks inside blocks such as IF...ENDIF, WHILE...ENDWHILE, SELECT MAX, etc. Empty coding blocks add no value and are considered maintenance

    overhead.

    COMMON PArT STruCTurE DEFINITION INCONSISTENT

    Identically Named Common Parts must have the same structure definition.

    COMPONENT NOT ASSIGNED TO AN ENHANCEMENT

    Function Module must be assigned as a component of a CMOD enhancement.

    CurrENCY CLAuSE When outputting numbers that are tied to currency, always use the CURRENCY formatting option. This will set the number of decimals according to the currency of the country.

    CuSTOMEr DEFINED MACrOS NOT rECOMMENDED

    Operational issues in Macros that cause Program Dumps are difficult to trace. Wrap the

    reusable code in a method instead.

    DANGErOuS HIDE ON A FIELD SYMBOL

    Avoid using field symbol with a HIDE statement. If field symbol is not assigned,

    unpredictable results can occur

    DATA VArIABLES - uSE OF DEFAuLTS

    Do not use implied defaults on data declarations. Be explicit when TYPING your data

    variable. Always Specify the TYPE and Length

    DATA VArIABLES - uSE OF TYPE VS LIKE

    Use keyword TYPE when declaring data objects rather than LIKE (which is an old

    convention). LIKE should only be used when a data declaration refers to an existing data

    object defined in your program. LIKE is also commonly used for declaring the line type of

    an internal table i.e. LIKE LINE OF.

    TYPE is a common convention found in most other modern programming languages.

    Note: In OO porgramming, any reference to a dictionary type MUST use the keyword

    TYPE. LIKE will fail syntax check.

    DATABASE ACCESS INSIDE A LOOP Avoid database accesses inside a loop to minimize performance issues.

    DATABASE uPDATE WITHOuT uPDATE MODuLE

    Updates to the database should be encapsulated in V1 or V2 Update function modules. This provides full recovery and logging of activity when performing INSERT, UPDATE,

    MODIFY and DELETE of Database tables.

  • Reference Guide | 5ABAP Coding Standards

    CONFIDENTIAL ABAP Coding Standards - Reference Guide. Vers. 2.0

    Copyright 2010. CodeExcellence Inc. All Rights Reserved

    DATABASE uPDATES INSIDE A LOOP

    Replace Updates inside a loop with a single set level process update to the Database outside of the loop. This will reduce the trips to the Database and improve performance.

    DATE FOrMAT uNSuPPOrTED Do not reference unsupported date formats. The only valid supported date formats are found in USR01-DATFM

    DEAD CODE Remove unused code unless it is required for documentation.

    DIrECT uPDATE TO SAP TABLE Under no circumstances should any program directly update SAP delivered tables. Updating of SAP tables should be performed using pre-delivered API's that perform the

    update

    DuPLICATE DEFINITION Avoid Duplicate Definitions for all objects and declarations. It is redundant, causes Maintenance issues, and possible extraneous processing with unpredictable results.

    DuPLICATE WHEN CONDITIONS Never duplicate a WHEN condition. Unexpected program behavior could result with duplicated WHEN conditions.

    DYNAMIC CALLS TO PrOGrAMS Dynamic Calls to programs can lead to production failures if program or object does not exist. Without proper exception handling, this is a dangerous practice.

    DYNAMIC TABLE ACCESS Always Include Exception Handling when accessing Tables Dynamically. Dynamic Calls can lead to production failures if the call can not be resolved or object does not exist. Dynamic Table access can be a very a dangerous programming practice if proper exception handling is not in place.

    ESSENTIAL PrINT PArAMETErS Essential Print Parameters are missing. Unexpected results can occur without the essential print parameters. Essential required print parameters are:

    Name of printer (DESTINATION)

    Number of copies (COPIES)

    Spool identification: Name of spool request (LIST_NAME)

    Text of spool request (LIST_TEXT)

    Spool control: Deletion of the spool job after print output (RELEASE)

    Archiving mode (ARCHIVE_MODE, 1 = print, 2 = archive, 3 = print and archive)

    New spool request, this means do not append to an existing request (NEW_LIST_ID)

    Format specifications:

    Column number of a print page(LINE_SIZE)

    Lines per page (LINE_COUNT)

    Print output format (LAYOUT)

  • Reference Guide | 6ABAP Coding Standards

    CONFIDENTIAL ABAP Coding Standards - Reference Guide. Vers. 2.0

    Copyright 2010. CodeExcellence Inc. All Rights Reserved

    EXCEPTION HANDLING - uSE CLASS BASED

    Use Class Based Exception Handling Techniques. CATCH ENDCATCH is obsolete.

    Errors should be anticipated and handled in all program code. The nature of errors varies and could be caused by incorrect implementations internal to the program or external interactions such as input errors or unexpected resource limitations (E.g. files,

    memory).

    All runtime errors (E.g. zero divide, conversion errors, ) raise class-based exceptions

    and should be captured and handled in program code with the CATCH statement in a TRY/ENDTRY control block.

    EXCEPTION HANDLING GENErIC MESSAGE AFTEr FuNCTION CALL

    Generic Messaging after a function call is not recommended. Anytime the PATTERN

    function in the workbench is used to insert a function, it automatically inserts a generic message of the form:

    "MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2,

    sy-msgv3, sy-msgv4.

    This statement assumes that SY variables have been filled with meaningful values by the

    function itself. However, often times, this is not the case and the message will be meaningless.

    The generic message should only be used in the case where the function and all nested functions that are called use the Message...Raising format consistently throughout the function chain. The Message...Raising format sets the sy-message and other sy variables.

    Only then, can you be assured that a generic message statement can be used to present a proper error message. However, since this situation is most likely not the case, a good developer will handle the message themselves and not count on the generic format to provide a meaningful message relevant to the situation.

    EXCEPTION HANDLING MISSING Or WrONG EXCEPTION

    ABAP Statements that can potentially cause program dumps require that the correct exception for the statement as per the SAP Help must be caught and handled to avoid dump situations. Ensure that a Try/Endtry is in place to catch the exception.

    Note: CX_ROOT as a catch all exception is not a recommended practice.

    This check ensures that the CORRECT EXCEPTIONS are handled for the following

    statements: REPLACE, COLLECT, SORT, FIND, ASSIGN, CREATE, Dynamic SELECT,

    and Dynamic METHOD

    EXCEPTION NOT CAuGHT Or DECLArED

    The exception is neither caught nor declared in the RAISING clause of the procedure.

  • Reference Guide | 7ABAP Coding Standards

    CONFIDENTIAL ABAP Coding Standards - Reference Guide. Vers. 2.0

    Copyright 2010. CodeExcellence Inc. All Rights Reserved

    EXCEPTION NOT PrOCESSED There may be cases where SAP delivered functions do not have defined exceptions. It is still recommended to provide exception handling when Calling the function. This enables that the code still works without a run-time error in the event that SAP adds an exception

    to the Function Module interface. For example the application of an OSS Note is able to

    introduce a new execption for the function module. Setting all exceptions to 0 in the CALL FUNCTION statement is not a good practice because it basically ignores the

    exceptions.

    The programmer should always check the exception returned from a function. DO NOT

    not count on an importing parameter being returned to the calling program as a sign of successful execution. An assumption holds true that a field is not set if an exception is

    returned, but that could change during a future enhancement of the function.

    Exception: Excluded from this rule are system functions that don't return any exceptions, i.e. function module DEQUEUE. For these system functions that do not have defined

    exceptions, it does not make sense to check for SY-SUBRC after the function call.

    Note: Customer defined functions should always have Exceptions defined.

    Recommendation:

    ==> If a function module has exceptions defined, you have to handle them. An empty IF

    statement is not enough

    ==> If a function module has no exception defined, CodeExcellends recommends

    using EXCEPTION OTHERS = 1 and handle the exception

    ==> If a function module has no exception defined, and the programmer is not

    using EXCEPTION OTHERS = 1 you can't check sy-subrc after the function module call

    since the sy-subrc will not be set by the function call

    EXTErNAL CALLS External calls to subroutines are forbidden. In the case of short dumps, the ability to debug external calls is restricted and Production support therefore becomes more difficult.

    EXTrACT FILES Extract Files are considered Obsolete. There is no need to use this old style array processing technique

    EXTRACT files are a convenient way of dealing with internal tables of different structures

    that have same or similar keys. The same can be achieved with internal tables. Only one EXTRACT file can be used per program.

    FIELD IS uNKNOWN Only fields that are defined or in a specified table can be referenced. Any reference to fields that do not exist will cause syntax issues.

    FIELD NOT A PArAMETEr Or SELECT OPTION

    The parameter / select-option in the SUBMIT statement does not exist on the selection

    srceen of the called program. Verify that the parameters and select options match between the SUBMIT statement and the called program selection screen

  • Reference Guide | 8ABAP Coding Standards

    CONFIDENTIAL ABAP Coding Standards - Reference Guide. Vers. 2.0

    Copyright 2010. CodeExcellence Inc. All Rights Reserved

    FIELD SYMBOL NOT ASSIGNED A field symbol was defined but not assigned. If the field symbol is not used, then it should be removed.

    FILE OPErATIONS - LOGICAL FILE NAMES

    Use the logical file concept instead of hard coded physical file names. The function FILE_

    GET_NAME must be used to translate the logical file name to the physical path and file

    name.

    Logical filenames are mapped to physical filenames using transaction FILE. Dynamic

    parameters are available to i.e. client, instance, etc. to ensure file names meet file naming

    conventions and the programs that use the files work across all system boundaries.

    FuNCTION GrOuP INCONSISTENT All components of a Function Group must pass internal consistency check. If the consistency check error occurs, it is possible that some internal objects have been corrupted. This can result in the function module not being stored in the database table TFDIR or possibly stored under a different name.

    FuNCTION MODuLE OBSOLETE Using Obsolete Function Modules should be avoided. It will cause upgrade issues as they are not forward compatible or supported by SAP.

    FuNCTIONS WITHOuT EXCEPTIONS

    When Calling a function, always include the exceptions clause. There is no value in checking sy-subrc if the exceptions clause is not part of the CALL Function statement.

    Don't add an empty IF SY-SUBRC = 0 ... ENDIF block or a CHECK SY-SUBRC = 0 after

    a function call without exceptions. A function should be defined with exceptions unless it

    is a special purpose function such as update task, asynchronous, RFC, etc.

  • Reference Guide | 9ABAP Coding Standards

    CONFIDENTIAL ABAP Coding Standards - Reference Guide. Vers. 2.0

    Copyright 2010. CodeExcellence Inc. All Rights Reserved

    HArD CODING When the same text literal is used repeatedly in an arithmetic or logical expression, define the value as a Constant instead of a text literal and name the constant descriptively.

    This check determines if their is hard coding contained in the following statements: SELECT, DELETE, SORT, LOOP, WHEN, IF, READ.

    Corporate processes change. So do the business values used in daily operations. For example, it is very common to experience changes to business config items such as

    document types, org level definitions, cost centers, company codes, plants, etc. Therefore

    it is highly recommended to avoid Hard Coding of any business values required in your

    program.

    Where possible, use existing SAP tables to provide business values to the program and use a SELECT statement to retrieve those values into an internal table. If an SAP table is not available with the required values, then it is advised to build a custom Z* table to

    contain the required business values. There are significant benefits to this approach

    when it comes to maintenance. When a business value changes, then maintenance is performed on the custom table (once) rather than all instances of programs that use the

    business values. Customer defined business type tables should try to use data elements

    that are already used in like fields in other SAP tables.

    If the above approach is not followed and it is decided to hard code business values in the program then at minimum, the hard coded value should be defined as a constant and

    named descriptively.

    HYPHEN DETECTED Avoid the use of the hyphen in a declared variable name. It is normally used as a dereferencing operator.

    IGNOrED EXCEPTIONS CLAuSE The EXCEPTIONS clause is ignored for asynchronous update function modules. Clean up the function by removing the superfluous Exceptions.

    ILLEGAL NuMBEr CONVErSION Non numeric fields should not be converted into numbers. This could result in a run time error with a program dump.

    ILLEGAL uSE OF OFFSET A length declaration is required when using offsets.

    INCOMPATIBLE uSING/CHANGING The actual parameter category must match the formal parameter category. This means that if a parameter is passed as a USING, it shoud be received as a USING.

    INCOMPLETE ACCESS TO INTErNAL TABLE

    Avoid Indirect Index Access to an Internal Table. All INSERT statements need to be either

    placed within a LOOP or use a specific row INDEX. Duplicate records for an unique

    internal table index will cause a program dump. For all internal table operations make sure the system is clearly able to identify the internal table row where the change, delete or insert needs to occur.

    INCOMPLETE Or MISSING WHErE CONDITION

    Use a WHERE condition with appropriate indexes where possible.

  • Reference Guide | 10ABAP Coding Standards

    CONFIDENTIAL ABAP Coding Standards - Reference Guide. Vers. 2.0

    Copyright 2010. CodeExcellence Inc. All Rights Reserved

    INCOrrECT MESSAGE PArAMETErS

    WITH fields must match placeholders defined for the MESSAGE statement.

    INCOrrECT uSE OF FOr ALL ENTrIES

    When using the addition FOR ALL ENTRIES in ITAB, the driver table ITAB and table

    fields must have the same type and length.

    INEFFICIENT COPY (LArGE DATA OBJECT)

    Avoid poor performing assignment of large amounts of data. This is especially critical in the case of deep structures or large data elements.

    INTErNAL TABLES - DELETE ADJACENT COMPArING

    DELETE ADJACENT DUPLICATES should always be explicit by using the COMPARING

    clause, even if there is only one field in the ITAB.

    INTErNAL TABLES - LOOP AND ASSIGN

    Use LOOP AT ITAB and assign to a field symbol. This technique improves performance

    on medium and large ITABs.

    INTErNAL TABLES - MODIFY IN LOOP ASSIGN

    When using LOOP AT ASSIGNING, MODIFY and UPDATE statements are redundant.

    The Assigning is a pointer. Any changes to the row become explicit on the row being processed so there is no need to issue the update or Modify commands.

    INTErNAL TABLES - NESTED LOOPS

    Nested Loops can cause inefficient processing when programmed incorrectly. Use

    parallel cursor technique for nested loops with standard tables. It is the most efficient

    means of processing Nested Loops. The performance gains are significant.

    INTErNAL TABLES - SINGLE rEAD DO NOT LOOP an itab to retrieve a specific record when a single READ will do the job.

    INTErNAL TABLES - TrANSPOrTING

    Use the TRANSPORTING clause with READ and MODIFY wherever possible to transport

    only the fields necessary.

    INTErNAL TABLES SOrT BY BrEAK LEVEL FIELDS

    FOR BREAK LEVEL processing with the AT command inside a LOOP at ITAB, sort by the break level fields before entering the LOOP.

    INTErNAL TABLES SOrTING When sorting internal tables, always be explicit by using "SORT BY key1 keyn", never just "SORT" on its own.

    INTErNAL TABLES WITH HEADEr Avoid any syntax that results in obsolete tables with headers such as OCCURS 0 or With Header Line or Perform Tables.

    INTErNAL TABLES WITH HEADEr IN FOrM

    Do not use TABLES statement when passing internal tables to FORMS. This will result in an internal table with Header being created local to the form. ITABS with header are obsolete.

    INTErruPT COMMANDS RETURN Statement should be used to exit a procedure (FORM, FMOD, METHOD). EXIT should not be used.

    If a conditional statement (i.e LOOP, IF, etc. ) is in the procedure, the programmer can

    code either EXIT or RETURN depending on the desired exit scenario i.e. is the intent to

    leave the conditional block or to exit the procedure

  • Reference Guide | 11ABAP Coding Standards

    CONFIDENTIAL ABAP Coding Standards - Reference Guide. Vers. 2.0

    Copyright 2010. CodeExcellence Inc. All Rights Reserved

    INVALID PrOGrAM TYPE FOr INCLuDE

    Include program type attribute must be correctly set to indicate it is an Include

    INVALID SLIN PSEuDOCOMMENT Use valid PSEUDOCOMMENTS as defined by SAP when marking code for inspection bypass.

    INVALID VALuE SPECIFICATION Use valid VALUE specifications for a FIELD.

    IS ASSIGNED IS ASSIGNED check should be issued prior to a field symbol assignment in the Read TABLE statement. If the field symbol is referenced and has not yet been assigned, a

    short dump will occur.

    ITAB MODIFY INDEX IN LOOP Avoid LOOP at ITAB and then modifying by index in the loop. This can lead to unpredictable results and performance costs.

    Avoid inserting new lines while looping over an internal table. Instead, add new lines inside the LOOP using the APPEND statement to add the new line at the end of the

    internal table.

    ITAB OVErWrITE IN LOOP During LOOP Processing of an internal table, do not delete or overwrite the table that is being Looped.

    KEY NOT SPECIFIED IN A BuFFErED TABLE

    Use keys in tables to avoid bypassing the buffered table. In the case of Generically

    Buffered Key Area, specify all keys that are part of the generic buffered area as defined

    in the technical setting of the table.

    LIST PrOCESSING EVENTS List Processing Event Blocks are obsolete. All report programming should be performed using the ALV object model. Therefore, any list processing events that are traditionally used for controlling lists in classic programming are considered obsolete. This would include Top-of-Page, End-of-Page, New-Page, at pf . Selection screen events are still

    used to support selection screens.

    LOGICAL OPErATOrS INSTEAD OF WOrDS

    Use operators ( >=, ,

  • Reference Guide | 12ABAP Coding Standards

    CONFIDENTIAL ABAP Coding Standards - Reference Guide. Vers. 2.0

    Copyright 2010. CodeExcellence Inc. All Rights Reserved

    METHODS FOr MODuLArIZATION For Modularization and re-usability, always use methods as your first choice over FORMS (subroutines) and function Modules. In OO context, FORM...ENDFORM is considered

    obsolete.

    MISSING CrITICAL PrOGrAM ELEMENT

    Critical Program Elements are missing and therefore the program can not compile. (This

    includes sub objects such as screens, tables, Includes, forms, parameters, etc.). All

    referenced components must exist.

    MISSING MANDATOrY PArAMETEr IN FuNCTION CALL

    All mandatory parameters must be specified when calling a function.

    MOVE TO INSTEAD OF WrITE TO Use MOVE TO instead of WRITE TO when possible.

    NATIVE SQL Avoid using native SQL to ensure database independence and avoid incompatibilities between different database tables.

    NESTED LOOP Nested loops can cause performance issues. This applies to any form of Nested Loop i.e. WHILE or DO inside of a Loop or a LOOP inside of WHILE or DO. In the case of a Loop within a Loop, explore the possibility of using a Parallel cursor technique where checks are in place to ensure that the inner loop record exists using READ and uses EXIT to exit

    inner loop when keys are different. With large tables, the performance gains are significant.

    NO rEAD ACCESS TO FIELD Validate that the FIELDS are used in the program. It is posible that it is referenced indirectly such as parameter passing to a procdure. If the field is not used anywhere,

    remove unreferenced fields from the program.

    NO WHErE CONDITION IN A LArGE TABLE

    Where statements should always include index fields for performance reasons, especially

    for LARGE tables.

    OBJECT uNrEFErENCED Or uNuSED

    Remove all program elements that are unused or unreferenced.

    OBSOLETE ABAP Avoid the use of obsolete ABAP statements.

    OFFSETS AND SuBSCrIPTING Avoid code that uses specific offsets for the purpose of subscripting into parts of a structure. Offset coding is problematic when coding in a UNICODE environment since

    characters are not represented by a single byte and can therefore lead to incorrect data sub stringing. Offset coding is also very problematic when dealing with dates where users are able to change their date format.

  • Reference Guide | 13ABAP Coding Standards

    CONFIDENTIAL ABAP Coding Standards - Reference Guide. Vers. 2.0

    Copyright 2010. CodeExcellence Inc. All Rights Reserved

    ON CHANGE OF IN LOOPS Avoid using ON CHANGE OF statement for Break level processing. Unpredictable results can occur with ON CHANGE OF because it is specific to a single field whereas the AT...

    ENDAT triggers a break when any change occurs in the field specified or fields left of the

    specified field.

    OPEN DATASET with ENCODING The ENCODING option determines the character representation of the content of the file. At minimum, you must specify the encoding option DEFAULT or UTF-8.

    When Opening a Dataset for Output in Text Mode, the file should be Opened with the

    Encoding Option UTF-8 and With Byte Order Mark(BOM). This will create a proper

    Unicode non platform dependant file with a BOM, consisting of 3 bytes at the beginning

    of the file that identifes the file as UTF-8

    When opening a Unicode File (UTF-8) for Input, specify the addition SKIPPING BYTE-

    ORDER MARK so that the BOM is skipped and NOT considered part of the file content.

    The file pointer will be set immediately after the 3 byte BOM

    OPEN DATASET with MESSAGE Authorization and permission access at the OS level is one of the most frequent causes of an OPEN statement failing. Always Use the Message clause on the OPEN statement

    to trap operating system errors. This approach traps the Operating System error and therefore goes beyond the standard subrc checking. Subrc only tells if the operation was successful but does not give the speicfic reason why the operation failed. The Message

    Clause reports specific application server errors such as permissions, file existence,

    etc.

    OuTPuT POSITION 0 NOT ALLOWED

    Avoid using output position 0.

    OVEr rIDE VIOLATIONS Used to bypass detected rule violations due to technical reasons

    PArAMETEr PASSING BY rEFErENCE

    As a general rule, PASS BY REFERENCE should be used where possible for performance

    reasons. This test examines whether it is possible to improve the performance of a parameter transfer for a method, form, function module, or event. However, there are programmatic reasons for using by VALUE. i.e. in the case of a RETURNING parameters,

    it is always by VALUE. Specifically, the test checks for the following situations:

    The type of the VALUE parameter contains tables whose row type in turn contains

    internal tables.

    The type of the VALUE parameter contains tables with different row types.

    The type of the VALUE parameter contains strings, but no tables.

    The parameter type is a flat field with a length > 100 bytes/characters.

    The type of the VALUE input parameter is a flat field with a length

  • Reference Guide | 14ABAP Coding Standards

    CONFIDENTIAL ABAP Coding Standards - Reference Guide. Vers. 2.0

    Copyright 2010. CodeExcellence Inc. All Rights Reserved

    PArAMETEr uNTYPED All parameters must be typed to enable static type checks. If a type cannot be declared, use the type ANY.

    PArAMETErS - uSING DOES NOT MATCH CHANGING

    USING parameters must match CHANGING parameters.

    POSSIBLE LOSS OF DB CurSOr The database cursor may be lost as a result of certain call sequences that contain COMMIT. For example, a Commit work or PERFORM inside a SELECTENDSELECT

    is problematic.

    POSSIBLE SEQuENTIAL ACCESS ON AN INTErNAL TABLE

    Avoid sequential access on internal tables. On large tables, this can be costly. A sequential access will happen if internal tables have incomplete keys or in the case of standard tables, Binary Search clause is missing. For internal tables avoid using the obsolete version of READ TABLE ... WITH KEY. Instead specify an appropriate UNIQUE or NON-

    UNIQUE INDEX as part of the internal type definition and use READ TABLE ... WITH

    TABLE KEY. Note: The addition BINARY SEARCH is still required to avoid sequential

    reads when using STANDARD tables.

    This rule also applies to change or delete access in internal tables, e.g. deleting data in an internal table with a WHERE condition results in a full scan of the internal standard table. A better solution is to define the table as a SORTED table with a nonunique (or

    unique) key. In the DELETE statement use the WHERE condition in combination with

    WITH TABLE KEY and the key fields. Now the access will be able to leverage the sort

    sequence.

    PrIMArY KEY FIELDS NOT FuLLY SPECIFIED

    Always specify the fields of a primary key in a single record buffered table.

    PrOBLEM WITH INDEX ACCESS TO INTErNAL TABLE

    When using Non-Numeric Index Value to delete rows from an internal table, use the

    format 'DELETE ITAB FROM work areas'

    rAISE FOr EXCEPTION MISSING An EXCEPTION that is part of the exception group never gets raised. This exception should be removed from the exception group if it is never used.

    rAISE ONLY IN FuNCTION GrOuPS RAISE statements should only be used in FUNCTION groups.

    SECONDArY INDEX IN A CLIENT SPECIFIC TABLE WITHOuT CLIENT FIELD

    Secondary indexes for CLIENT SPECIFIC tables should have client as the first field of

    the secondary index.

  • Reference Guide | 15ABAP Coding Standards

    CONFIDENTIAL ABAP Coding Standards - Reference Guide. Vers. 2.0

    Copyright 2010. CodeExcellence Inc. All Rights Reserved

    SELECT FOr ALL ENTrIES When using "Select... For all Entries" the following rules MUST be followed:

    Check to make sure driver ITAB is not empty

    Always SORT the ITAB (driver table) by keys.

    Specify all keys used in the WHERE clause.

    DELETE Adjacent Duplicates Comparing the keys that were sorted.

    All Primary Key Fields must be in the Select List.

    The WHERE clause must include INDEX fields to make use of index scan.

    If index fields are not available as part of the WHERE clause, then it is better not to use

    FOR ALL ENTRIES. The better option would be a SELECTWHERE into an ITAB.

    Any further filtering can be done using ABAP Memory

    SELECT INTO COrrESPONDING Avoid the use of SELECT ... INTO CORRESPONDING especially for tables with a large number of fields. The CORRESPONDING clause results in DB overhead. The

    corresponding target fields are not know until runtime and therefore need to be rebuilt at

    execution. The has a negative effect on performance.

    Instead, Specify the individual fields required and define the work area to correspond to

    the fields being selected.

    SELECT SINGLE EXPECTED FOr SINGLE rECOrD BuFFErED TABLE

    Use SELECT SINGLE with full key when accessing Single Record Buffered Table or

    buffer will be bypassed.

    SELECT WITH A SuBSEQuENT CHECK

    Avoid the use of CHECK statements after a SELECT. Instead use a WHERE statement to filter the data.

    SELECT WITH AGGrEGATE FuNCTION ON BuFFErED TABLE

    Use aggregate functions with caution in a buffered table. Aggregate functions will cause the buffer to be bypassed which leads to increased processing to retrieve data from DB instead of buffer.

    SELECTION SCrEEN FIELDS The purpose of a selection screen is to provide the user with flexible options to enter values that will influence the outcome of the program execution. Create variants, where

    possible, and have the user community use the variant to set screen default values. Exceptions to this rule are non-business technical related parameters i.e. Logical File

    Names, etc.

    SELECTION TEXT NOT MAINTAINED Be sure to maintain the Selection text for all selection fields and parameters. In multilingual systems the DDIC reference flag should be set wherever possible to leverage existing

    SAP translations from Data Dictionary ==> Reduces translation efforts

    SELECTION TEXT WITHOuT SELECTION FIELD

    Selection Texts that are defined but not used or referenced on a selection screen should

    be removed from the text element list.

  • Reference Guide | 16ABAP Coding Standards

    CONFIDENTIAL ABAP Coding Standards - Reference Guide. Vers. 2.0

    Copyright 2010. CodeExcellence Inc. All Rights Reserved

    SINGLE PErIOD LINE Eliminate lines of code that contain a single period.

    STANDArD INTErNAL TABLE PrOCESSING

    When Processing a Standard Internal Table:

    Always use the Binary Search option i.e. READ ITAB with KEY Binary Search.

    READ the Internal Table by Keys

    Be sure that table is sorted by same key that is used in the READ WITH KEY statement

    (or data will be missed)

    STATEMENT uNrEACHABLE Unreachable statements have been detected. i.e. after Jump statement such as RAISE: EXIT. Ensure that all statements can be reached.

    STruCTurES OBSOLETE Use type statement to build local structures. Structure statement is obsolete.

    SuPPrESSED ruLE SUPPRESSED RULE

    SuSPICIOuS ErrOr NEEDS FURTHER INVESTIGATION

    SYSTEM CALL Never make calls directly to System Functions for production programs. System Calls and functions are reserved exclusively for SAP use.

    SYSTEM FIELDS FLAGGED OBSOLETE

    Never Use obsolete system fields. Check Dictionary structure SYST. The data element

    description indicates which fields are flagged as obsolete.

    SYSTEM FIELDS PASSING & uPDATING

    Never update system fields or pass system fields to Procedures (FORMS, METHODS,

    Function Calls). There are some syst fields that are exempt: SY-LSIND,

    SY-SuBrC NOT HANDLED Always Check Return Code SY-SUBRC after critical operations SQL, ITAB Operations, Function Calls, etc.

    TEXT ELEMENT IN POOL NOT uSED TEXT ELEMENT from text pool in program is not used.

    TEXT ELEMENT INCONSISTENT Text Element is defined differently in the program and the text pool

    TEXT ELEMENT MISSING Char. strings without text elements cannot be translated in a multi-lingual environment.

    TEXT LITErAL SHOuLD BE NuMErIC

    It is more efficient to use numeric literals directly. Text literal must be converted to a

    numeric literal.

    TrANSPOrTING NO FIELDS It does not make sense to use TRANSPORTING NO FIELDS if the fields need to be referenced

    uNCOMPILABLE CODE Use the Code Inspector to eliminate all SYNTAX errors, including syntax warnings.

    uNDEFINED INTO FIELD Into LISTS must be of the form (f1...fn) with all fields defined.

    uNDEFINED TITLE TITLEBARS should have a title defined.

  • Reference Guide | 17ABAP Coding Standards

    CONFIDENTIAL ABAP Coding Standards - Reference Guide. Vers. 2.0

    Copyright 2010. CodeExcellence Inc. All Rights Reserved

    uNDESIrABLE LANGuAGE ELEMENTS

    A number of ABAP statements are no longer compatible with the latest SAP technologies. These statements still work in a SAP GUI transaction environment but have been replaced

    by newer much more efficient and flexible solutions. Programming syntax that is

    considered problematic are as follows:

    ABAP list processing statements like WRITE, FORMAT, SKIP, NEW-LINE etc. in

    programs should instead using ABAP List Viewer classes for list display functions.

    The use of CALL TRANSACTION USING to submit a BDC. This technology relies on

    screen layouts. If a screen layout changes, the code stops working. This makes the code highly unreliable during the application of Support Packs, Enhancement Packs and Upgrades. Therefore programs need to use BAPIs to submit business functions.

    Submitting database operations directly from ABAP by calling database functions

    directly (e.g. 'DB_COMMIT"). Any use of these functions introduces a high risk of

    transaction inconsistencies and needs to be avoided. Similarly, programs need to avoid direct access to data dictionary function modules changing the databse tables, e.g. DD_CREATE_TABLE.

    Programs need to avoid using position operations in sequential files. If necessary files

    should be processed sequentially instead of controlling the read position (SET

    DATASET, GET DATASET, TRUNCATE DATASET).

    Database SELECTs need to avoid retrieving a single line for Update. This operation

    includes an implicit database lock quickly leading to bottenecks and deadlocks. Instead use ENQUEUE functions to lock an object in SAP, read it and subsequently update it.

    Avoid using SELECT .. BYPASSING BUFFER.. since this access avoids using the

    database cache causing performance issues and inconsistencies.

    Avoid using native SQL to ensure database independence and avoid incompatibilities

    between different database tables.

    uNICODE FLAG NOT SET All programs in a Unicode system must have the UNICODE flag set ON. If the flag is not set in a Unicode system the program dumps with a syntax error. The Unicode flag can

    only be set once the program passes the Unicode syntax check (transaction UCCHECK).

    In a non-Unicode system the flag does not have to be set, but as of ERP 6.0 SAP only

    supports single code page non-Unicode ERP system. Any multi code page system has

    to be Unicode. Therefore it's generally better to always turn this flag on

    uNIT CLAuSE When outputting numbers that are tied to units of measure, always use the UNIT formatting option. This will set the number of decimals according to the unit of measure being output.

    uPDATING and PASSING GLOBAL FIELDS

    Avoid the declaration of global variables as much as possible. Avoid passsing Globals to

    Subroutines and Methods.

    Avoid setting global variables in too many places. A preferred approach to setting globals is to use dedicated recognized methods that follows best practice naming convention such as SET_*

  • www.codeExcellence.com

    Tel: (403) [email protected]@codeExcellence.comHeadquarters in Calgary, Alberta, Canada

    Reference Guide | 18ABAP Coding Standards

    CONFIDENTIAL ABAP Coding Standards - Reference Guide. Vers. 2.0

    Copyright 2010. CodeExcellence Inc. All Rights Reserved

    uSEr SPECIFIC CONTrOL Avoid using references to specific USERS or USERIDs for any reason.

    VALuE ASSIGNMENT EXCEEDS LENGTH

    VALUE specifications must not exceed the length of the defined field or type.

    VArIABLE NAME INCOrrECT Variable names should not begin with %_*. Prefix %_* is reserved for internal names.