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

Programming Standards

Document Change Control

Release
1.0 1.1

Description
First relese Changes to the India development and authorization check

Created By
Kannan Gopal Kannan Gopal

Date

Reviewed By

Date

Approved

Date

CONTENTS
1 2 3 4 Overview Naming conventions Development Guidelines Documentation Within the Code
4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 4.10 4.11 4.12 Program Header Subroutines Events Modules Module Pool Programs Function Pool (Group) Programs Subroutine Pool Programs Class Pool Documentation Interface Pool Documentation Changes and Enhancements User Documentation Text Elements
Page 1 of 20

Programming Standards
5 6 7 8 Message Classes Changing SAP Code Database tables Database Updates
8.1 8.2 8.3 8.4 8.5 8.6 8.7 Database Operations (SQL) Open SQL VS. Native SQL Join Indexes Subqueries Accessing data in Packages SAP Index tables Defining Internal Tables Working with Internal Tables

Usage of Internal table types


9.1 9.2

10 11 12 13 14 15 16 17
17.1 17.2

Function Module Exception Handling Reusing Existing Data Elements/Domains vs. Creating New Ones Adding Customer Fields to SAP Delivered Tables Data Elements in the Data Dictionary Program Layout Parameters and Selection Screen Fields Local vs. Global Variables Modularization
Subroutines and Function Modules Function Groups

18 19

Authorization Check Country Specific development

Page 2 of 20

Programming Standards

Overview
The purpose of this document is to detail uniform program standards for ABB and to provide guidelines and useful information for programmers in the SAP environment. Programming standards are needed to ensure the readability and maintainability of custom development programs 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 standard generic 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 All names (variables, programs, function modules, classes, and so on) in English Use meaningful names (for example, use lv_material not lv_m) Wherever possible, use glossary terms (for example, lv_company_code not lv_bukrs) Use underscores (_) to separate the different words in compound names Mandatory X X X

Write comments and documentation in the coding in English X Write comments in the coding as though you were explaining the program to a X colleague 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 X not available in customer systems) 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 refinements CRM: 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 use overly complex joins) Page 3 of 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 Define constants globally (multiple use, simple central modifications!) Use TABLES statements only when absolutely necessary If you have to use TABLES statements, always use them globally Allowed, for example, in function groups with database access Not necessary for select statements of the SELECT INTO wa ENDSELECT type Do not use data structures from TABLES statements directly X X X

Use internal tables without headers X This also applies, for example, to the transfer of internal tables to function modules Headers (internal tables as parameters of a function module are always created with headers within the function module) are also not allowed within the function module Note: Tables with headers are no longer supported in an ABAP-OO context If sorted data is required, the tables in which the data is managed must always be stored in SORTED TABLES Reason: Considerable improvement in performance when accessing data, because binary searches are possible There is also no need to sort using SORTED BY statements Keep the number of global variables to a minimum Use local variables wherever X possible In this context, the following applies for function modules: Define variables and structures globally only if several function modules need them to transfer data or if they function as a memory aid! Define locally in the individual function modules any variables that are used by several function modules independently, but individually are of local importance only Modules should consist of subprogram calls (PERFORM statements) only, meaning that the coding should run only in the subprogram Reason: 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 them after an appropriate amount of time has elapsed Be aware of layer models: The different layers should be clearly separated from one another. Only specific interfaces must be used to communicate between the layers. Example of a layer model: User Interface Layer Business Logic Layer Database Layer ( There are detailed descriptions in CRM, for example) Never make changes to the database directly. Always use update modules that call X the update task. Function modules must always be used in read accesses (SELECT) to databases X Page 4 of 20

Programming Standards
Benefits: Enables maintenance to be carried out centrally Buffering Never read function codes, screen numbers, or transaction codes Reason: Leads to problems with generic functions and makes maintenance difficult If system variables (sy-repid, for example) are used as parameters, they should always be stored in local variables Reason: System variables are reset when other programs or function modules are called, 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 calls Reason: A separate roll area is opened, and there is a danger that different roll areas 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) see the reuse library Initialize new DDIC table fields only in exceptional cases, meaning when it is absolutely necessary Leads to unnecessary type conversions Leave new fields with a ZERO value in case an initialization in accordance with the data type is not explicitly necessary (time during upgrade, memory usage) Number fixed values consecutively or start with the letter A and work through the alphabet Reason: Since the software is used worldwide, there is no point in trying to identify fixed 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, and then use this include when you define the tables This 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 MARAMATNR) Screens: Always define screen fields with a DDIC reference Never use global variables as screen fields Always 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) in separate function groups Modifications to the flow logic of generated maintenance screens should take place only 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 objects Reason: Performance the maintenance function modules should not be loaded in a read access (the complete function group is always loaded when a function module is accessed) Always deal with exceptions! X If an exception has not been dealt with, the situation must be documented clearly! Rules for Form Routines and Function Modules Rule Page 5 of 20

Programming Standards
Use a generated header (document header) for a new form X This 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 Parameter Transfer X 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 as import / export parameters Whenever possible, avoid using global variables for hidden parameter transfers! If global 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 Store part-functions in their own form routines Omit form routines to optimize performance only in cases where mass processing is the main 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 Code


The programs should have a header as defined in the template A comment box should precede the subroutine describing in brief the functionality Include full line comments to explain blocks of code.

Program Header
At the top of programs, function modules a header has to be included. Page 6 of 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 above code 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.

Subroutines
A comment box must precede the subroutine. The comment box should contain the name of the subroutine and a 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 Programs


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

Function Pool (Group) Programs


Function groups programs are containers for function modules and are maintained by the function builder. Like Module Pool programs, they only contain INCLUDE statements. They should not be changed manually.

Page 7 of 20

Programming Standards
Subroutine Pool Programs
Subroutine pool programs are collections of FORM routines called from external programs. The general form naming conventions and documentations are to be followed.

Class Pool Documentation


Class pool documentation is maintained in the Class Builder. For custom classes, the documentation should have the following format.
*----------------------------------------------------------* CL ZCL_nnnnnnnnnnnnnnnnn Ownership: 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 Documentation


Interface pool documentation is maintained in the Class Builder. For custom interfaces, the documentation should have the following format.
*----------------------------------------------------------* IF ZIF_nnnnnnnnnnnnnnnnn Ownership: Created by: ________ Created on: mm/dd/yyyy. Version: n.n *----------------------------------------------------------* Modification Log: Date Programmer Correction 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 *----------------------------------------------------------*

Description

Changes and Enhancements


If a modification is made to an existing custom ABAP program, an entry should be made in the modification log with 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

Programming Standards
Example: IF SY-SUBRC NE 0. Exit. ENDIF. DevK9000045 DevK9000045 DevK9000045

User Documentation
User 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 program documentation 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 user should 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 path described above or though Program Documentation icon which is automatically added to the report selection screen Application Toolbar in the GUI interface.

Text Elements
Each ABAP should have associated text elements and constants from the source code placed within the Text Elements 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 preferred as they can be easily made multilingual. The alternative is coded headings, which require further coding for each language supported. Note: Any data entered here will not show up in the report header if the program uses the No 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 should always 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 multilingual clients. 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 and needs to be changed.

Page 9 of 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 customer issues. Although, the customer may also make the determination after reviewing all options, that changes to SAP programs are needed. Whatever the source, there must be tight controls when making changes to SAP code and such changes must first 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 section in the Program Header (see below), detailing the date the changes were made, who made the changes, the Repair number, the issue number the change relates to (found in the Change Management Logs), the OSS Note Number 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 by SAP, 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. *<< END OF INSERT OSS 1234567 DEVK900012

Database tables
Custom database tables should be defined as client dependent. Database tables are normally defined as client-specific tables (first key-field must be MANDT with reference to data element MANDT). Tables requiring maintenance must have a table maintenance view generated. If the table should be maintainable, a table maintenance view must be generated via the corresponding function in the data dictionary (assign maintenance modules to a dedicated function group). Table maintenance views must be assigned to a table authority group In this case, you must assign a table authority group in the table maintenance screen in order to restrict table maintenance to the authorized users. Z Customizing tables should be buffered. Since buffered tables reduce access times the Z tables that are used for customizing should be buffered

Page 10 of 20

Programming Standards Database Updates


Update modules should be used for database updates. They should be bundled in proper LUW for transactional integrity. 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 statements for 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 the outer table. Select <Field> vs. Select* Using Select field1 field2 .. Instead of Select * is significantly faster if the table contains a large number of fields
Example: Recommended: SELECT FIELD1 FIELD2 FIELD3 FROM TAB1 INTO TABLE IT_TAB1 WHERE FIELD1 IN O_FIELD1. Not Recommended: SELECT * FROM TAB1 INTO TABLE IT_TAB1 WHERE FIELD1 IN O_FIELD1.

Recommendation: 1. Use Select <field>: 2. Table consists of a large number of fields 3. 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 <Field> into vs. Select <Field> into corresponding fields
Example: Recommended: SELECT FIELD1 FIELD2 FIELD3 FROM TAB1 INTO TABLE IT_TAB1 WHERE FIELD1 IN O_FIELD1. Not Recommended: SELECT FIELD1 FIELD2 FIELD3 FROM TAB1 INTO CORRESPONDING FIELD OF TABLE IT_TAB1 WHERE FIELD1 IN O_FIELD1.

Existence check Avoid using Select COUNT (*) to verify the existence of records in a table as the COUNT function scans through all records within a table. Sort during Select vs. ABAP sort There are two ways of sorting application data. One is sorting on the database server and the other is sorting on the application server.
Recommended: Example: Sorting data after select statement SELECT FIELD1 FIELD2 FIELD3 FROM TAB1 INTO TABLE 1T_TAB1 WHERE FIELD1 = 'X'. SORT IT_TAB1 BY FIELD1.

Page 11 of 20

Programming Standards
Not Recommended: Example: Sorting data in the select statement SELECT FIELD1 FIELD2 FIELD3 FROM TAB1 INTO TABLE IT_TAB1 WHERE FIELD1 = 'X' ORDER BY DISPO MATNR.

Select distinct The DISTINCT addition to the SELECT statement allows you to remove duplicates from a set of results during a SELECT.
SELECT DISTINCT FIELD2 FROM TAB1 INTO TABLE IT_TAB1 WHERE FIELD1 = 'ABC'.

Disadvantages: 5. Requires sorting on database server and adversely affects overall system performance if no index can be used 6. When using DISTINCT the database is always accessed directly by passing the SAP buffer
Alternative approach: SELECT FIELD2 FROM TAB1 INTO TABLE IT_TAB1 WHERE FIELD = 'ABC'. SORT IT_TAB1 BY FIELD2. DELETE ADJACENT DUPLICATES FROM IT_TAB1 COMPARING FIELD2.

Array updates All Database manipulations in SAP (UPDATE, INSERT, DELETE) can be executed one record at a time or through 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. ENDLOOP UPDATE 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 executed 8. SY-DBCNT Contains the number of successfully updated records

Open SQL VS. Native SQL


Developers are not supposed to use native SQL.

Join
Since joins are executed at the database level they limit network traffic and increase efficiency. A disadvantage of join is that it bypasses SAPs buffer at application server level.
Example: Use of INNER JOIN SELECT T1~AUART T2~MATNR INTO TABLE IT_ORDER FROM VBAK AS T1 INNER JOIN VBAP AS T2 ON T1~VBELN = T2~VBELN WHERE VBELN IN O_VBELN.

Page 12 of 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 fields or a clean secondary index. This will also be taken care of by the cost based optimizer in most of the cases 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 is suggested 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.

Indexes
The 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 using the 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 to reformulate such conditions into forms relevant to the index, such as an IN condition. For example, you should avoid 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 using the 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 to reformulate such conditions into forms relevant to the index, such as an IN condition. For example, you should avoid the following SELECT statement, which has an inner OR:

Subqueries
A subquery is a SELECT command within another SELECT, specified in the WHERE condition, that checks whether data from a database table or view meets certain conditions. In addition, subqueries can be used in UPDATE 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

Programming Standards
This version of the SELECT statement was the only way to join tables until SAP release 3.0E. It is recommended that the SQL JOIN be used. However, this is an alternate method of joining tables that may be used 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 for referencing in the FAEI) as possible. If duplicate entries are not deleted, identical data is read unnecessarily from 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 in SQL. This is absolutely required to avoid data loss since the DB interface in R/3 returns unique sets of the result set to the application program. Failing to ensure this may cause problems when you want to get all records from a 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 scans for each FAEI packet. Even if it does index range scan, it is better to get data from the small DB tables by individual 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 table scan 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 FAEI packets. 7) FAEI works best when retrieving a small percentage of data from a Database table. When a large percentage of data is needed, consider getting data out of the DB table without FAEI implementation, and then do additional filtration 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 its own package size
Example: SELECT FIELD1 FIELD2 FIELD3 FROM TAB1 INTO TABLE IT_TAB1 PACKAGE 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 tables


Review and evaluate the use of alternate index tables before creating indexes on any existing SAP transaction tables. Some examples of index tables: VAKGU Sales Index: Quotation Validity VAKPA Sales Index: Orders by Partner Function VAPMA Sales Index: Order Items by Material VBOX SD Document: Billing Document: Rebate Index VEPVG Delivery Due Index VETVG Delivery Due Index for Stock Transfer Page 14 of 20

Programming Standards
VKDFS VLKPA VLPMA VRKPA VRPMA VTRDI EKKI EKUB BSAD BSAK BSAS BSIA BSID BSIK BSIM BSIP BSIS BSIW BSIX SD Index: Billing Initiator SD Index: Deliveries by Partner Functions SD Index: Delivery Items by Material Sales Index: Bills by Partner Functions SD Index: Billing Items per Material Shipment Planning Index Purchasing Condition Index Index for Stock Transport Orders for Material Accounting: Secondary Index for Customers (Cleared Items Accounting: Secondary Index for Vendors (Cleared Items) Accounting: Secondary Index for G/L Accounts (Cleared It Archive Index for FI Documents (Outdated! See ARCH_IDX) Accounting: Secondary Index for Customers Accounting: Secondary Index for Vendors Secondary Index, Documents for Material Index for Vendor Validation of Double Documents Accounting: Secondary Index for G/L Accounts Index table for customer bills of exchange used Index table for customer bills of exchange used

Usage of Internal table types


Use the following guidelines when deciding between the different table types 11. Type STANDARD should be used as default type 12. Type HASHED if the internal table contains a large number of records and your program requires a large number of primary (unique) key accesses 13. 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 Index option

Defining Internal Tables


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


Modifying Components of an Internal Table With the MODIFY variant MODIFY itab ... TRANSPORTING f1 f2 ... WHERE condition, the task of updating a set of lines of an internal table can be accelerated considerably. Especially if tables embedded in the lines can be 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 component DATE are modified. Modifying all components through loop processing Mass modify for internal table should be preferred over modification inside a loop Appending an internal table to another internal table
Example:

Page 15 of 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 to TAB_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 append APPEND LINES OF TAB_SRC TO TAB_DEST.

Delete duplicates from a sorted internal table To 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 condition


Example: Table TAB_DEST is filled with 1000 entries of 500 bytes each, 250 of which match the WHERE condition Not Recommended: Delete using loop processing LOOP AT IT_TAB1 WHERE FIELD1 = VAL1. DELETE IT_TAB1. ENDLOOP. Recommended: Delete using the WHERE clause Let the kernel do the work DELETE IT_TAB1 WHERE FIELD1 = VAL1. Delete using conditional loop processing LOOP 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_TAB1 IF 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 table ENDIF. Recommended: IF TAB1[ ] is initial. * Empty internal table ENDIF.

Reading from an Internal Table For reading the table the preferred method is using index. If it is not possible then binary search may be used. Page 16 of 20

Programming Standards
Key Search
READ TABLE TAB ASSIGNING <S_TAB> WITH KEY <key field> = <value>.

Key/Binary Search
READ TABLE TAB ASSIGNING <S_TAB> WITH KEY <key field> = <value> BINARY SEARCH.

Search with Table Index


READ TABLE TAB ASSIGNING <S_TAB> INDEX <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 order Not Recommended: Join two internal tables using key search LOOP AT IT_TAB1. READ TABLE IT_TAB2 WITH KEY K = IT_TAB1-K CHECK SY-SUBRC = 0. ENDLOOP. Recommended: Join two internal tables using key/binary search Note: 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 cursor Note: 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 Table


Examples: 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 condition Table 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

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 <FS_TAB1>. LOOP AT IT_TAB2 ASSIGNING <FS_TAB2> FROM I2. IF <FS_TAB2>-K <> <FS_TAB1>-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 since we don't have detailed messages in the functions. In order for the generic syntax to work below the function must make use of the Message...Raising format 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-msgno WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4. ENDIF.

This is not allowed unless the Message...Raising format is used consistently throughout the function. The following is the recommended way of handling message. Correct:
CALL FUNCTION 'Z_FUNCTION_1' EXPORTING p_val1 = lv_val1 p_val2 = lv_val2 TABLES t_tab1 = lt_tab1 t_tab2 = lt_tab2 EXCEPTIONS Error1 =1 Error2 =2 OTHERS = 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

Programming Standards Reusing Existing Data Elements/Domains vs. Creating New Ones
Below are general rules on when to create a custom data element/domain and when to reuse an existing SAP data 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 as CHAR1, 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 Tables


Append structures structures must be used when adding custom fields to SAP delivered tables.

Data Elements in the Data Dictionary


Each new custom Data Elements each Data Element will require Meaningful description This 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 source code 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 the output 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 transaction Mode, packet size setting. Avoid the use of OBLIGATORY. The use of required fields on the selection screens can cause problems for variant definition. Any validation of select-options or parameters should occur in the AT SELECTIONSCREEN event.

Local vs. Global Variables


A clear demarcation has to be made between variables that are used globally and locally. Variables used locally should be defined as local variables and variables used globally should be defined as global variables.

Page 19 of 20

Programming Standards Modularization


Subroutines and Function Modules
Subroutines 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. Separate subroutines 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 Groups
Function Groups must be used to store Function Modules, which are commonly called within the same logical unit of work. All Functions within the same Function Group share a global memory area. When a program calls a 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 commonly called individually, it should be the sole member of a Function Group. Dynamically called Function Modules must 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 Global Data, 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 cause e.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 is saved or displayed. The authorization object is ZPRCHK_NEW. The authorization fields available for the check are TCD Transaction Code PRCTR Profit Center SPART Division WERKS Plant VKORG Sales Organization EKORG Purchasing Organization

Country Specific development


The country specific developments must run just for the country specific processes. This is ensured by having the check for country in each of the developments. A function module will return the country code. The process logic 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 is company code, profit centre, plant or division. The output provides the unique country code for the respective input.

Page 20 of 20

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