Z abap coding_standards_v2_0_t

191 views

Published on

ZABAP CODING STANDARD

Published in: Automotive
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
191
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
5
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Z abap coding_standards_v2_0_t

  1. 1. ABAP Coding Standards Reference Guide August 2010
  2. 2. 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.
  3. 3. 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.
  4. 4. 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
  5. 5. 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 there’s 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.
  6. 6. 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)
  7. 7. 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.
  8. 8. 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
  9. 9. 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.
  10. 10. 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.
  11. 11. 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 LOOPAT … 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
  12. 12. 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 LOOPat 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 ( >=, <=, =, <>, >, <) rather than the obsolete words GE, LE, EQ, NE, GT, LT LOOP IN SELECT/ENDSELECT Avoid LOOP/ENDLOOP blocks within SELECT...ENDSELECT statements. They are very performance expensive. MAINTAIN TEXT ELEMENTS TEXT Element is not defined in text pool in the original language. MESSAGE TRUNCATED Message parameter should not exceed field length specification. SAP only provides a maximum length of 50 characters for any message parameter (SYST-MSGV1-MSGV4). Please make sure that all fields and texts that are passed into a message variable are no longer than 50 characters
  13. 13. 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.
  14. 14. 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 <= the parameter PARAMETER PASSING IN FORMS Define USING parameters by VALUE. Define CHANGING and Internal Tables by REFERENCE.
  15. 15. 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 SELECT…ENDSELECT is problematic. POSSIBLE SEQUENTIAL ACCESS ON AN INTERNAL TABLE Avoid sequential access on internal tables. On large tables, this can be costly.Asequential 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.
  16. 16. 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 SELECT…WHERE 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.
  17. 17. 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.
  18. 18. 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_*
  19. 19. www.codeExcellence.com Tel: (403) 875-0809 info@codeexcellence.com support@codeExcellence.com Headquarters 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.

×