Copyright Notice and Disclaimer

COPYRIGHT NOTICE and DISCLAIMER:

(c) Copyright 1998, 1999, 2000, 2001, 2002, 2004, 2005  by the Massachusetts Institute of Technology, Cambridge, Massachusetts, USA.

M.I.T. hereby grants to any organization producing ABAP code the right to use this document or parts thereof for noncommercial internal use subject to M.I.T.'s disclaimer of liability contained herein and provided that all copies shall bear an M.I.T. copyright notice in the form provided above.

This documentation is provided "as is" without warranty of any kind, expressed or implied, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose, and further without warranty that use of this documentation will not infringe the patents, copyrights or other intellectual property of third parties. In no event shall M.I.T., its trustees, directors, officers, employees or students be liable for incidental or consequential damages of any kind, including, but not limited to damage or injury to property and lost profits, regardless of whether M.I.T. knew or had reason to know of the possibility of such an occurrence. No permission to use the name of Massachusetts Institute of Technology or M.I.T. or any adaptation thereof is granted to any user of the ABAP code or documentation, except for use in the notice of copyright provided above. Massachusetts Institute of Technology, M.I.T. and MIT are registered trademarks of the Massachusetts Institute of Technology and may not be used in any manner without the prior written permission of the Massachusetts Institute of Technology.

I. HOW TO UPDATE THIS GUIDE

If you have questions about topics in this guide, would like to suggest changes, or provide new topics to be included, please submit the topics and details about the updates to sap-dev-standards@mit.edu.

Revision History

Revision Date Description of Changes
8
13-Feb-2006 Added two sections under Coding Standards; "Interface: Processing Inbound & Outbound Files" and "Uploading and Downloading files between the SAPgui & the R/3 System." Updated Appendix B (2 character codes for application areas), adding BD and EP.  Updated Appendix C (Development Classes), adding development classes ZBD0 and ZEP0. Some UI clean up.
7
31-Aug-2005 Removed the red arrows in the Table of Contents that indicated previously modified or added sections.  Added a requirement for setting the P_HNCAT and P_BOUNCED_MAIL parameters to the Z_SENDMAIL function module.  Added instructions for restricting access to HR data.  Updated Appendix B (2 character codes for application areas), adding BU, EH, and FF.  Updated Appendix C (Development Classes), adding development classes ZBUD0, ZEH0, ZFF0, ZPE0, ZPM0, and ZPY0.  Added a new section on the naming conventions for "Check Modules for External Commands". Added Appendix D (Approval process for Direct Updates & Mods). Replaced obsolete mailing lists with active ones. Replaced ZJOBRUN with ZJOBRUN2 table details.
6
1-Oct-2002 Updated the table of contents. Modified the ZJOBRUN section. Updated Appendix B (2 character codes for application areas).  Updated Appendix C (Development Classes). Made many spelling corrections. Fixed one of the links in the table of contents so that it would link to the correct section.
5
1-Feb-2002 Modified the Introduction/Purpose section.  Added a link to "Revision History" and reversed the order of revisions so that the latest revision is at the top.  Updated the table of contents.  Modified the section concerning making programs obsolete.  Added a section on "Guidelines For Deleting Old/Unused ABAP Code".  Modified the section on "Dates : Output in reports".  Added a section on "Termination Codes in Cost Objects".  Added a section on the "Communication Between Foreground and Background Processes".   Added a section on the "Choices of Currency Fields".  Added a section called "Intercepting & Logging Emails via Z_SENDMAIL".  Added a section on "Restricting the Capabilities of Select Options in ABAP Programs".  Added a section on the "Enterprise Structure Attribute Table".  Added a section "Naming Conventions in ABAP Objects".  Added a section called "General Toolkit for Multiple Enterprise Structures".  Added a new major section in the table of contents called "User Interface Standards", and moved the sections "GUI: SAP Style Guide", "GUI : Screen Painter Resolution" into it.  Added a link to the "MIT Web Site Look and Feel Standards" and moved this section under the "User Interface Standards".  Added a section regarding the use of Radio Button Groups.  Added a section on "Naming Conventions in ABAP Objects".  Updated Appendix B (2 character codes for application areas).  Updated Appendix C (Development Classes).  Made many spelling corrections.  Updated 4.5 references to relevant 4.6 references.  Added tables and more bulleted sections for better readability.  Modified coding examples to incorporate some of the correct documentation standards
4
6-Mar-2000 Added disclaimer. Added section on function modules. Added section on making programs obsolete. Added section concerning request & task naming. Added section for the creation of custom tables. Updated source code documentation section. Added information about messages and program variable naming. Updated performance checklist. Updated section concerning legacy conversion function modules. Added some application area two-letter abbreviations. Added naming standards for function module IO. Added requirements for handling 40-character program names. Added list of development classes. Added section for processing the results of a BDC call transaction. Note that new or modified sections are highlighted in the table of contents with a "".
3
17-Sep-1998 Performance Section update, New Tips & Tricks, Application abbreviations added (PM, RQ, BP), New document layout and navigation features.
2
22-May-1998 Document layout changes and spelling corrections.
1
15-May-1998 Initial (post-review) distributed version.

II. Introduction/ Purpose 

This document was created to outline several naming standards, programming standards, and best practices in ABAP programming and provide guidelines for ABAP development for MIT. These are MIT's "ABAP/4 Development Standards" and contain MIT-specific programming conventions and techniques. The topics include:

As standards are developed, this guide will be updated on an ongoing basis.

The document is intended for use by ABAP developers as a guide for MIT-specific developments and enhancements to R/3. The user of this document should be familiar with basic concepts of R/3 and should have taken a training class equivalent to SAP20 R/3 Overview.

To request clarification of these issues or to suggest other topics to be covered, please send mail to: sap-dev-standards@mit.edu.

The purpose of this document is as follows:

The standards have been developed in conjunction with a number of supporting function modules, custom tables, and (sometimes) complete programs. It was worth investing the development effort in those supporting tools, because many people will use them. Similarly, since the tools already exist, are known to work, and are being maintained, it would be foolish not to use them whenever the circumstances for which they were created arise.

III. BACKGROUND

SAP development at MIT has been done by a combination of consultants, contractors and employees who have had varying levels of experience with other SAP projects and with other MIT projects. A number of the people who worked on our implementation are no longer at MIT. We need to make the code developed for MIT's SAP project as easy to understand and easy to maintain as possible. In order to do that, the ABAP developers at MIT have written this set of development standards.

MIT-ABAP Mail List

Anyone doing SAP development at MIT should subscribe to the MIT-ABAP mail list. This includes employees, contractors, consultants, project leaders, and project managers. The list is intended for all development issues including configuration, workflow, report writer, report painter, basis, system administration, documentation, support, training, management, and master data maintenance.

To subscribe to the list, send e-mail to LISTSERV@MITVMA.MIT.EDUwith the body of the message containing the single line "SUBSCRIBE MIT-ABAP [Your real name]". (without the quotes or brackets and filling in your name.)


IV. CODING STANDARDS


General Standards

1. One command per line
Each ABAP/4 command consists of a sentence ending with a period. Multiple commands can be on one line; however, as a standard start each new command on a new line. This will allow for easier deleting, commenting, and debugging.
2. Indented source code
The ABAP/4 editor has a "Pretty Printer" command to indent by 2 positions specific lines of code and add subroutine comments. Event keywords are typically not indented.
DATA: BEGIN OF tab OCCURS 100,
       f1 LIKE sg-field1,
       f2 LIKE sg-field2,
     END OF tab..

DATA: f1 TYPE I,
      f2 TYPE I.

START-OF-SELECTION.

GET table.

  IF f1 = f2.
    f1 = 0.
  ELSE.
    f1 = 1.
  ENDIF.

SELECT * FROM table WHERE

  field1 EQ sg-field2 AND
  field2 BETWEEN sg-field5 AND sg-field6.

    MOVE ...

    APPEND ...

ENDSELECT.

END-OF-SELECTION.

LOOP AT tab.
  AT NEW f1.
    CASE F1.
      WHEN ... 
        WRITE: ...
      WHEN ...
        WRITE:/ ...
    ENDCASE.
  ENDAT.

  WRITE:/ f1, f2, ... 

ENDLOOP..
3. Variable naming
ABAP/4 variable names can be up to 30 characters for DATA fields and subroutines and up to 8 characters for SELECT-OPTIONS and PARAMETERS, therefore, as a standard make the names descriptive. Since SAP segment/table-field names are hyphenated with a '-' (dash), use an '_' (underline) to separate the words for program-specific variables. Whenever possible, the LIKE parameter should be used to define work fields.
DATA: MAT_DT LIKE SY-DATUM,
     DAYS TYPE I,
     HOLD_ACCTNO LIKE sg-field1,

     GROSSAMT(10) TYPE P DECIMALS 2,
     GROSS_PERCENT(3) TYPE P DECIMALS 2,
     NET%(3) TYPE P DECIMALS 2.



Some variable types should be prefixed with a specified letter or letters:
Variable Type
Prefix
selection screen parameter
p_ or a_
form routine parameter
p_
select-options
s_
ranges
r_
internal tables (global)
t_
internal tables (local)
it_
constants
c_

Subroutine examples:
FORM CALCULATE_MATURITY_DATE.
    MAT_DT = SY-DATUM + DAYS.

ENDFORM.

or for COBOL-like standards:
FORM F100_CALCULATE_MATURITY_DATE.
 

4. Reusable code
If a block of code is executed more than once, it should be placed in a subroutine at the bottom of the code. This makes the code more readable, requires less indentation, and is easier to debug since the debugger can jump through an entire subroutine via a PF key. Also, when possible parameters should be passed to and from subroutines to make the purpose easier to understand and reduce the need for global variables. Always document the purpose of each parameter.
5. Parameter passing in subroutines
Whenever possible use a TYPE or LIKE statement when specifying the formal parameters of a subroutine.  This is a good programming style, plus it allows the ABAP compiler to generate more efficient code (which can increase performance up to a factor of two). For example:

form <subroutine> tables p_tab1   like <tab1>[]

                   using  p_param1 like <data>
                          p_param2 like <dd-field>
                          p_param3 like <dd-structure>
                          p_param4 type <standard data type>
                          p_param5 type <user defined data type>
....

endform.
6. Text handling
INCLUDE files can't define their own Text Elements - any Text Elements to which they refer must be defined in the main program which invokes the INCLUDE file. Therefore, if it is possible that an INCLUDE file may be invoked from more than one main program, constant text that is used within the INCLUDE file should be defined with the CONSTANTS statement.

In cases other than INCLUDE files, constant text which is printed in a report can be stored as Text Symbols. 
There are two ways that you can code references to these Text Symbols, either using TEXT-xxx or using '...'(xxx). Here, xxx stands for a 3-digit number, and ... for the text of the Text Symbol.

The first form requires that you separately define a Text Symbol for number xxx. If xxx isn't a defined Text Symbol, the output is empty. The second form improves the readability of the program. The text between the single quotes should correspond to the text stored as the value of the Text Symbol. If it does not, the system uses the text stored for the Text Symbol. Exception: If there is no text saved under number xxx, the text between the single quotes is used.

Example: Text symbol number 001 has the text 'Please enter your name'. The following commands:

WRITE: / TEXT-001,

       / 'Please enter your name'(001),

       / 'What is your name?'(001).

all have the same output: "Please enter your name". In the ABAP Editor, you can compare the texts used in the program with the texts stored as Text Symbols by choosing "Goto -> Text elements -> Text symbols", then "Utilities -> Adjust -> Text symbols", then selecting the "Text symbols defined repeatedly/differently in program" radio button and clicking on the "Edit" soft button.

The advantages to the '...'(xxx) form are readability and that the Text Symbol only needs to be maintained for multi-lingual clients (for those installations which use multiple languages). The advantage to the TEXT-xxx form is easier maintainability if TEXT-xxx is coded several times in the program and it needs to be changed.

7. Usage of UserIDs in programs
In no case should a production program or function contain a UserID as either literal or constant data. In the development system it may be necessary to code temporary breakpoints for specific UserIDs, however, these debugging techniques must be removed before the program will be transported.
8. Messages
Declare the message class in the report statement: While it is possible to specify the message class each time a message is output, it is easier to specify it once in the report statement. You can still use a message in another class than the one defined in the report by adding the class in parentheses after the message.

Report ZZTEST1 message-id zz.

message e001.

message e012 with p_user.

message e231(zl).

Avoid using generic (placeholder) messages in programs.

Example: message class ZZ:

001 Your work has been saved!

...

999

Instead of "message s999 with 'Your work has been saved!' ", you should use message s001.

To help locate an appropriate message, you can use the "pattern" function in the ABAP editor. Choose "other pattern" and type in "find message" (or pick it from the drop-down list), and press enter. Follow the instructions from there to find a suitable message to paste into your program. If you can't find a suitable message, you should create one in message library ZZ, unless your program is a "one-time" use program and it is unlikely that the message will be re-used.

Use long text where appropriate.

If your program is to output a specific message which requires further explanation, create a new message and fill out the long text form. When the user clicks on the message the long text will be displayed.

Use the correct message type:

Type Description On-line action Background action
I
Informational Press ENTER to continue No action
W
Warning Correction possible No action
E
Error Correction required Program terminated
A
Abend Transaction terminated Program terminated
S
Success Message on subsequent screen No action

Note that all messages are logged in background by the background processing system.

Making Programs and Function Modules Obsolete

Steps to make a program obsolete:

  1. Verify that the program is not referenced by any other programs, transactions or dialog modules that are not obsolete in either the production or development environments. If it is, notify the person who requested the program to be made obsolete and stop here.

  2. Reconcile the development version with the production version, and revert development to the same version as production if it is different. (Use the Version Management function to do this). Make sure that the retrieved version can be generated without errors. If there are errors - return back to the original active version.

  3. If you have to go back to the previous version, make sure that any active development of an object in unreleased requests/transports is saved by releasing the request/transport.

  4. If the program is not a function module, go to transaction SE38, and put in the program name which is to be made obsolete.  Click on Attributes, and then click on "Change". Change the title of the program to start with the word "Obsolete". Change the Authorization Group to "ZINACTV0" (the last character is the digit ZERO), and the Application to "* Cross-Application". Attempt to change the Development Class to "ZZZ0" (the last  character is the digit ZERO). If you have problems changing the development class, go back to the ABAP editor initial screen. Click on "Goto" at the top of the screen, and then click on "Object Directory entry" on the dropdown. Make the change and save.

  5. Send all the information about the program (including by whom & when it was determined that this program is obsolete) to sap-obsolete-progs@mit.edu. Please be sure to send your e-mail before releasing the program from SF2.

  6. Transport the changes made to SF5 and Production.

Since SAP doesn't let us change the authorization group for one function module, we (MIT) are


using the following six steps in place of step 4 above to make a function module obsolete:

   4a. Under ATTRIBUTES tab, change the short text (i.e. one line description) of the function

       module to start with the word "Obsolete".

   4b. Use the editor function to make all the source code lines of the function module into

       comments.  (On the PC version of the ABAP editor, you can use Control-A to select

       all the code and Control-< to make all the selected code into comments. On the Mac,

       click on the first line of code, then click on the Select icon, then click on the last line

       of code, then click on the Select icon to select all the code. Then select the menu item

Utilities -> Block/buffer -> Insert comment*

      to make all the selected code into comments.)

      * NOTE: you cannot comment out the key lines Function/Endfunction.

   4c. Insert a comment at the top of the function module source code stating that the function
        module is now obsolete.

   4d. Put the following ABAP statement in the source code in order to force a short dump should
        someone try to execute the function module:

MESSAGE ID 'ZZ' TYPE 'X' NUMBER '132' WITH 'Function module'
    '<name of function module>'.

   4e. Use the ABAP Workbench command to mark the function module as obsolete. (Go to SE37,
       type in the function module name and click on the "change" button. Go to the "Attributes"
       tab. Select the menu item:

Function module -> Release -> Object obsolete

 Here is an example showing steps 4b, 4c & 4d:

FUNCTION Z_INSERT_TR_ACCOUNT .
*********** This function module is OBSOLETE ***********

MESSAGE ID 'ZZ' TYPE 'X' NUMBER '132' WITH
'Function module' 'Z_INSERT_TR_ACCOUNT'.

**"---------------------------------------------------------------------
*
**"*"Update function module:
**"
**"*"Local interface:
**"  IMPORTING
**"     VALUE(TRAV_ACC) LIKE  ZTRV1 STRUCTURE  ZTRV1
**"  EXCEPTIONS
**"      INSERT_ERROR
**"---------------------------------------------------------------------
*
*
*   MOVE-CORRESPONDING TRAV_ACC TO ZTRV1.
*   INSERT ZTRV1.
*   IF SY-SUBRC <> 0.
*     RAISE INSERT_ERROR.
*   ENDIF.
ENDFUNCTION.

Guidelines For Deleting Old/Unused ABAP Code

When maintaining a program, new code is written to replace older code. It is usually a good idea to comment out the code rather than delete it entirely. This serves 2 purposes: it makes the old code readily available in case there is a problem with the new code, and it serves as documentation of how the old code used to work. After a while, so much commented-out code can accumulate that it makes it difficult to read the program - that is, the accumulated commented-out code can become confusing rather than helpful. (Code that was once active generally should be carried as commented-out code in at least one transport before it is actually deleted, but this is not an absolute requirement.)

If, in the judgement of the programmer, the commented-out code is confusing rather than helpful, the old code may be deleted if ALL of the following four conditions are met:

  1. The code to be deleted has been captured in SAP version management as part of a released transport.

  2. You add text to the revision history stating which line numbers in a previous (specified) released transport you deleted and why you deleted them. It is very desirable that you also cite the last transport in which these items were active. For example, you might write "Deleted commented-out code on lines 1570 through 1620 of transport SF2K912345 in order to make the program easier to read. This code was last active as lines 1232 through 1282 in transport SF2911678.".

  3. The revision history of the program is reasonably complete with good explanations of what was added or deleted as part of each transport, as well as the functional consequences of that change (not just a generic comment like "fixed bug" or "added new features"). A revision history like this should be maintained contemporaneously with changes to the code. If you acquire maintenance responsibility for a program that is already in production and has commented-out code which is not described in the revision history, you don't have to retroactively document the effect of the commented-out code. You do have to add to the revision history a statement following the example in item 2 (above) and a statement of whatever you know (or can easily determine) about the intended effect of the commented-out code that you are deleting.

  4. (If applicable) When an algorithm or general approach is changed, comments should be added near the code for the new algorithm or approach describing:
    1. how the new approach differs from the old one
    2. the most recent released transport with the old approach
    3. the range of line numbers containing the code that implemented the old approach in the version included in the referenced transport

Authorization Groups

Authorization Groups permit users access to execute report-type programs from transaction SA38 (or SE38).  All MIT-written reports must have an explicit authorization group. There are 3 cases:

When choosing an existing authorization group to assign to a program, especially a program that does not have additional authority checks in the program itself, be sure that the people who will be using the new program already have access to the authorization group chosen. If they don't, it is very possible that the authorization group chosen is not appropriate for the program, as giving them access to the new program would give them access to the other programs the authorization group controls.

In summary, all MIT-written reports must have an explicit authorization group - either as the only authorization mechanism or in conjunction with some other authorization mechanism. The 'ZOPN2ALL' authorization group should be used where the intent is to allow everyone in the community to at least start the program (although another authorization mechanism may be used to further restrict who can perform particular functions or access particular data).

Authorizations : Usage of SAP objects

For any custom programming using authorization checks, developers must determine whether a standard SAP authorization object should be used, or if a custom object should be developed. Since the authorization object implementation typically comprises more business-related than technical issues, developers should consult with the business analysts responsible for the application in making this decision.

Restricting Access to HR Data

Because of the sensitivity of HR data, all custom-written programs that access HR data must restrict who can access the HR data. Four methods to accomplish authorization checks for HR data are listed below:

  1. Use function module HR_READ_INFOTYPE instead of direct SELECT statements when reading a specific infotype.

  2. Use logical database PNP to leverage SAP authorizations (caveat: performance can be slow)

  3. SELECT statements should only be used when the SAP documented data interfaces which incorporate the SAP authorization checks (Logical Databases, function modules, and BAPI's) cannot provide the functionality required. If it is necessary to use SELECT's, then you must perform your own AUTHORITY-CHECK on the data selected.

  4. Place a strict authorization group at the program (transaction) level. If a wide variety of data for a large group of individuals is needed in a single program, then this program must have a very strict authorization on who can run it (definitely not on any menu path).

Dates: Output in reports (Year 2000 compliance)

The preferred formats for representing a date in a printed report are either MM/DD/YYYY or DD-Mon-YYYY(where "MM" is the two-digit number of the month, "DD" is the two-digit number of the day within the month, "YYYY" is the four-digit year, and "Mon" is the three-letter abbreviation of the name of the month).

In any case, use of a 4-digit year is a requirement. (The preferred format for dates in input, i.e. "Feed", files is YYYYMMDD.)

The R/3 system is already year 2000 compliant. To preserve that compliance, whenever a date is written or read, the year field should contain four digits. The only exception to this standard is reading from or writing to external files, where the year 2000 restriction in the external system may be different. However, even in this case, if it is at all possible, it is desirable to allocate four digits for the year in the file layout.

Interface : Field sizes and layouts in data files

All external file layouts used for files transmitted to and from the R/3 system should be discussed with and approved by the Infrastructure (formerly Bridges) Team before the layout is finalized. This is to insure consistency in field conventions and file processing standards. The requirements for the following data elements are:

Interface : Dropbox mechanism for file interfaces

The dropbox is the standard method for data providers to automatically deliver files created outside of SAP as feeds into MIT's SAP R/3 environments. Data providers must be registered with the dropbox. These providers FTP data files to the dropbox. Based on a combination of file naming conventions and registered dropbox userids, the files are automatically delivered to the appropriate MIT SAP R/3 environment.

Detailed documentation on how to use this mechanism is located at http://web.mit.edu/ist/org/admincomputing/dev/dropbox.html

Interface : Processing Inbound and Outbound Files

What SAP application programmers do to process inbound files

More information on processing inbound files (pdf).

What SAP application programmers do to process outbound files

More information on processing outbound files (pdf).

Interface : Inbound interface filename determination from event

When an inbound interface program is initiated by triggering an SAP event, the filename is sent as an event parameter which should then be read by the interface program. An example of using this triggering and parameter passing method is outlined in program ZDMR0036 (in development system SF2).

Jobs : Tracking status using ZJOBRUN2

Many programs read input files or produce extracts from the R/3 and require detailed tracking data file names and error statuses (beyond the capability of the standard R/3 job scheduler). Even if the program doesn't need to keep track of file numbers or status, there are other reasons that a program might need to preserve some status information from one run of the program to the next. It also might be necessary to record some status information for easy access by a human being. To provide a common repository for job status, the ZJOBRUN2 table was created. All programs that need to track job status should read / write records to / from this table. New programs must not use text files outside of the R/3 system or other custom tables for this purpose. Programs that currently use methods other than the ZJOBRUN2 table to track status should be modified to use ZJOBRUN2 instead.

NOTE: ZJOBRUN2 is an new and improved version of the original ZJOBRUN table. The original table is still in use by older programs but should no longer be used for developing new programs.

Here is the layout of the ZJOBRUN2 table:

ZJOBRUN2 Table
FIELD DESCRIPTION SAMPLE RECORD
PROVIDER File Transfer Provider ehse
FEED File transfer Feed Code trq
BATCH Sequential number of the job run 145
DATUM Date of run 08/07/2004
UZEIT Time of run 06:30:13
PGNAM Program name ZPE_EXTRACT_TO_EHSWEB
FILE File Name dehsetrq.145.20040807063013
TIME File Time Stamp 20040807063013
EXTRD Date of Extract Creation 08/07/2004
EXTRT Time of Extract Creation 06:30:13
RECCOUNT Record counter – number processed 589
CREDIT Total Credits (if applicable) 116.00
DEBIT Total Debits (if applicable) 473.00
CNTRLREC Control Record 589
CTRL_CREDIT Total control Credits (if applicable) 116.00
CTRL_DEBIT Total control Debits (if applicable) 473.00
ERRCOUNT Error Counter – number or error records 0
ERR_CREDIT Total error credits (if applicable) 0.00
ERR_DEBIT Total error debits (if applicable) 0.00
ERRFILE Error File – location of error file on UNIX filesystem  
CURCY Currency Key USD
FILSTAT File Status G
REVIEW Review Flag  
TEXT Text – any additional text info  
UNAME User who executed the job ZZPEBATCH001

Master Data: Searching for a person's name in master data

Supervisor and addressee names are stored in SAP master data tables. Because it is possible for more than one person to have the same name, MIT ID is used to uniquely identify a person at MIT. The MIT ID of each cost object's supervisor and addressee is stored in table ZCOOBJECT. The master list of MIT ID's is kept in table ZMITID. Several MIT-developed function modules exist to allow programs to access these tables. They are outlined below.

In addition, collective search help ZMID is available for possible value help. It consists of two elementary search helps:


Master Data: Determining Cost Object Type, Company, and Validity

Function Module Z_CO_GET_COST_OBJECT_TYPE can be used to determine the type
of a cost object, verify that the cost object is valid, and determine the company code of which
it is a part. The function module Z_FI_VALIDATE_GL_ACCOUNT is the G/L account counterpart
to Z_CO_GET_COST_OBJECT_TYPE. Z_FI_VALIDATE_GL_ACCOUNT is called with a G/L
account number and a company code. Z_FI_VALIDATE_GL_ACCOUNT will indicate whether
the specified G/L account is valid in the specified company code and whether any flag is set which
obviously prevents posting to that G/L account. (Again, it is possible that even if no flag is set there
might be some other reason that a charge or credit can't be posted to the specified G/L account.)

Termination Codes in Cost Objects

This section describes TermCodes in Cost Object master data and the ZSTATUS field of ZCOOBJECT table entries describing those Cost objects. (Note: when there is no TermCode on a Cost Object that is the same as saying that the value of the Termcode is "space").

Term Code ZSTATUS Meaning
None/Space
X
Valid cost object
1*
X
Valid cost object
2*
X
Valid cost object
3
T
Valid Terminated Cost Object (No postings permitted)
4*
X
Valid cost object
8
8
Invalid cost object with no charges/credits posted
9
9
Invalid cost object with charges/credits posted

* = Was used to indicate a restricted state in the MIT classic system but it no longer has any special significance.

Invalid Cost Objects (Cost Objects with TermCode = ZSTATUS = 8 or 9) should be treated by almost all MIT custom programs as though the Cost Objects don't exist. The only programs that should take cognizance of these invalid Cost Objects are transactions ZCO2 and ZCO3 (for modifying and displaying Cost Object master data), program ZCO005F (the Trial Balance report), and some extracts sending data to the data warehouse.

Terminated Cost Objects (with TermCode = 3, ZSTATUS = T) are valid and may be reported on, but they may not have any charges or credits posted to them. It is permissible to "Park" a document with charges or credits to a terminated (TermCode = 3, ZSTATUS = T) Cost Object.

An alphabetic character in the ZSTATUS field of the ZCOOBJECT table indicates that the Cost Object described by that row is a valid Cost Object. A numeric digit in the ZSTATUS field of the ZCOOBJECT table indicates that the Cost Object described by that row is an invalid Cost Object. MIT's Master Data maintainers guarantee that if the same Cost Object number appears in ZCOOBJECT more than once, only one of those appearances will have an alphabetic character in the ZCOOBJECT-ZSTATUS field - that is, at any instant, there will only be one valid cost object with a given Cost Object number.

Most MIT function modules that return data about a Cost Object by looking it up in the ZCOOBJECT table will ignore any rows that have a numeric digit in the ZSTATUS field of the ZCOOBJECT table. If the only row for a particular Cost Object number has a numeric digit in the ZSTATUS field of the ZCOOBJECT table, the function module will raise an exception indicating that there is no valid Cost Object with that number.

Function module Z_CO_GET_COST_OBJECT_TYPE was originally written to return the type (cost center, internal order, or WBS) of a valid Cost Object. During the M.E.S. project it was enhanced to (optionally) return the company code of the Cost Object. It has been enhanced again to also (optionally) return the status of the Cost Object. The status is the contents of the ZSTATUS field of the ZCOOBJECT table. Currently the returned status will be either 'X' (for a valid non-terminated Cost Object) or 'T' (for a valid terminated Cost Object).

Attempts to post charges or credits to terminated (TermCode = 3, ZSTATUS = T) cost objects will be prevented by MIT's validation rules. However, some programs might find it useful to know before attempting to post that the posting will be prevented by MIT's validation rules. Such programs can check whether the status returned by Z_CO_GET_COST_OBJECT_TYPE is 'X' or 'T'. (Of course, even if the statusis 'X', there are many other reasons why it might not be possible to post charges or credits to the Cost Object.)

 

Dictionary: Table development standards


1. Table naming convention
Name the table as follows:
Position Usage
1 'Z'
2-3 Business area - see appendix b
4-16 Descriptive characters
2. Table definition convention
The first field defined for any MIT developed business application table should be: MANDT . This is the 'client' field, and makes the table specific to the client that it is used/modified in. The only exception to this might be certain infrastructure tables that might be defined. These would not be business application tables, however.
3. Maintenance settings
  "Tab. Maint. Allowed" 'X' or (blank)

Flag if maintenance with Data Browser (Transaction SE16) is allowed.

If this flag is set, the data in the table can be changed with the Data
Browser and if the user has the necessary authorization.

If the data records of the table can only be maintained by program or
table view maintenance (Transaction SM30), you may not set this flag.

Note: If there is a maintenance interface for the table view
maintenance, the Data Browser cannot be called for the table. In this
case the flag has no effect.

4. Delivery class
Class SAP definition Comments
A
Applic. table (master and transaction data) Should not be maintainable by SM30/SM31
C
Customizing table, maintenance only by customer, not SAP import Used for Control type info, should be maintainable by SM30/SM31
L
Table for storing temporary data, delivered empty Should not be used for MIT tables
G
Customizing table, protected against SAP Update, only INS all This is for use on Customizing tables developed in cooperation with SAP. SAP can INSERT entries into this type of table, but cannot change or delete any.
E
Control table, SAP and customer have separate key areas Should not be used for MIT tables
S
System table, maint. only by SAP, change = modification Should not be used for MIT tables
W
System table, contents transportable via separate TR objects Should not be used for MIT tables
5. Access Control - Authorization Group

This is not readily visible on the table definition screen. The definition of an Authorization Group, and assignment of one to a table, are functions done by R3-Admin. However, the identification of what that group should be is an Application Development issue. An Authorization Group has a 4 character name.

A recommendation for the name construction is 'Zxxy',

where:

CHARACTER VALUE COMMENT
1
Z
 
2-3
xx
2 character business area abbreviation; Example  GL = General Ledger
4
y
1 alphanumeric character to distinguish sub groups within the business area for tables with common characteristics, and common users

Authorization Group is an important attribute of a table; it is used in authorizations to grant display and update access to the appropriate SAP Users.

An authorization group should be assigned to an MIT table if: - it is a delivery class 'C' (or 'G') customizing table - it is an application data table (Del. Class 'A') for which access is to be restricted, even if a person has access to the application which displays / maintains it. - An Authorization Group is recommended for all MIT developed tables, to provide a mechanism for controlling access, even in cases where the table is thought to be 'public' or commonly displayable.

6. Summary

When you are developing a table in SAP, consider these questions and the answers you get for them:

  • Who should be able to see the contents of this table? - only people who have access to the transaction/report that use the table - small number of people - larger number of people - any SAP User.
  • How will entries be added/changed/deleted for this table? - by an application program only - by standard table maintenance only - by both standard table maintenance and the application.
  • Are entries in this table dependent on entries in another table or vice versa? Is this necessary for logical consistency? (If so, either a check table should be used to ensure this, or maintenance should only be done via an application specifically coded to ensure this relationship).
  • Who should be able to add/change/delete entries of this table? - only people who have access to the transaction/report that use the table - small number of people - larger number of people.
  • Is this table one of several that all share IDENTICAL access control requirements, and will ALL be: a. commonly viewable by the exact same group of people? b. commonly maintainable by the exact same group of people? (The groups referred to in a. and b. may or may not be the same group) With this information you can establish a matrix that defines - groupings of tables - types of access needed - groups of people to have each type of access.

 

Direct database updates of SAP standard tables

Under no circumstances should any program directly update SAP-delivered tables using the INSERT, UPDATE, or DELETE commands. SAP-delivered tables begin with all letters other than Y and Z, and they should only be updated using an SAP transaction. To automate updates to SAP tables via a program, you may use the CALL TRANSACTION command (or optionally create a BDC using SAP supplied functions, or use BAPIs).

More information is in Appendix D.

 

Processing error messages from BDC call transaction

R/3 has message libraries (or classes) containing numbered messages which may contain placeholders. The ABAP MESSAGE command allows the programmer to specify a message library, a message number and up to four values to be substituted for the placeholders in the message.

Sometimes an ABAP programmer needs to substitute values for the placeholders himself - for example to present the messages produced as the result of a CALL TRANSACTION.
It is strongly recommended that the ABAP programmer use the ABAP

"MESSAGE ID mid TYPE mtype NUMBER nr WITH f1 ... f4 INTO expanded"

command.

Function Modules

When a function module detects an error, it (typically) raises an exception to report the error back to the caller. If you use the ABAP "RAISE" command, the caller gets the number associated with the exception. It is strongly recommended that MIT-written function modules not use the ABAP "RAISE" command - but use the ABAP

"MESSAGE ID mid TYPE mtype NUMBER nr WITH f1 ... f4 RAISING exception"

command.

This form of the ABAP "MESSAGE" command is only possible within a function module or a method. It triggers the exception "exception". If the program calling the function module or method handles the exception itself, control returns immediately to that program. In this case, the export parameters of the function module are ignored. However, the calling program can refer to the system field values:

If the calling program does not handle the exception itself, the message is output. This allows MIT-written function modules to be as helpful as possible. The help is provided to the calling program (if that program decides to use the extra information) or to the people dealing with an eventual problem (if the program doesn't use the extra information).

Communication Between Foreground and Background Processes

This section discusses the "recommended" method of communicating information from a foreground process to a background process.

In some cases it is desirable to have an interactive program which acquires some data (perhaps by reading a file on the desktop machine, perhaps some by other means such as user entry or a selection controlled by user entry) and passes that data to a background job for further processing. There are several ways that the information could be passed. One method is to have the interactive program write a Unix file which the background job will read.  That is NOT recommended (any more). The following three methods are recommended. The first two methods assume that the interactive (foreground) job creates and SUBMITs the background job and can pass parameters to the background job by including the parameter values in the SUBMIT command.

This is an expanded description of method 2, above. Assume that an internal table named "t_itab" is defined (and loaded with data) in the foreground job and the internal table "t_itab" has exactly the same definition in the background job. In the foreground job:

TABLES INDX.                                   "Not required in 4.6C
DATA key like INDX-SRTFD.
EXPORT t_itab TO DATABASE INDX(ar) ID key.
    where "t_itab" is the name of your internal table,
          "ar" is a two-character constant of your choosing,
          "key" is a variable containing a unique key (up to 22
          characters long) that you created (you might want to consider
          using elements such as the user name, the date, the time, the
          work process number, the application server name, etc. to
          produce a unique key)
SUBMIT BACKGRND ... WITH A_KEY1 = key ... .

In the background job:
TABLES INDX.                                   "Not required in 4.6C
PARAMETERS: a_key1 like INDX-SRTFD NO-DISPLAY.
IMPORT t_itab FROM DATABASE INDX(ar) ID a_key1.
    where "t_itab" is the name of your internal table,
          "ar" is the same two-character constant,
          "a_key1" is the parameter into which the unique key was passed
After you no longer need the data, the program should
DELETE FROM DATABASE INDX(ar) ID a_key1.

Choice of Currency Fields

SAP Tables contain multiple monetary amounts for two reasons:

1.  The amounts are expressed in (potentially) different currencies.
2.  The amounts represent different costs, expenses, or balances.

This section deals only with item 1 - that is, it is intended to provide guidance in the selection of field(s) which use the current currency.  It does not deal with item 2 - the programmer or business analyst must determine which costs, expenses, or balances the program should be using.

Make sure that the correct monetary fields are used.

Generally, it is NOT the monetary amount in the field described as "document currency", "transaction currency", or  "object currency".

If you need guidance in selecting fields from a table not yet listed here, or you have information about "monetary" fields not listed here, please contact either your FI-CO technical resource or Technical Services.
TABLE TABLE DESCRIPTION  MONETARY FIELD TO USE * FIELD DESCRIPTION
BSEG Accounting Department Segment DMBTR Amount in local currency
COEP CO Object: Line Items(by period) WKGBTR Total value on CO area currency
COSP CO Object: Cost Totals for External Postings  WKG99 Total value on CO area currency
COSS CO Object: Cost Totals for Internal Postings WKG99 Total value on CO area currency
GLT0 G/L Account Master Transaction Figures HSL99 Total Transactions in the period in local currency
RSPCO Project Info Database: Cost,Revenues,Finances WLP99 Period value in Ledger currency

*  The '9' 's in this column stand for a given period (1 through 16).

Required Parameters To Z_SENDMAIL

The majority of E-Mail sent from the MIT R/3 systems is sent via custom function module Z_SENDMAIL. After it was put into production, some additional input parameters were added to Z_SENDMAIL. Since Z_SENDMAIL was already being called by production programs, the new input parameters had to be added as optional parameters. However, any new or recently modified programs that call function Z_SENDMAIL are required to supply

Regarding P_HNCAT, if you do not find a mail handling category to fit your needs at E-mail Handling Categories , request a new mail handling category by sending mail to tech-services@mit.edu and then use the assigned value for the P_HNCAT parameter.

The address supplied in the P_BOUNCED_EMAIL parameter should be the address of a list of people who can take action to fix whatever problem caused the mail to bounce. Usually, this should be a mail list that is monitored by process owners who can investigate an undeliverable message or correct an invalid address. In general, the address supplied in the P_BOUNCED_EMAIL parameter should be one of the following (in order of preference):

  1. A mailing list of people from the business process side who can recognize and have the ability to resolve the issue of a bounced E-Mail message. For example, CAO maintains master data including cost object approvers. If a message to someone in the role of cost object approver bounced, the bounce should be directed to a list of appropriate people in CAO, so that the master data can be updated.
  2. A mailing list of people from an Admin Computing support or project team who can resolve the bounced mail.
  3. "sap-bounces@mit.edu". Currently, this mail will go to Carolyn Fuller, David Rosenberg, Wai-Ming Li, and Kevin Lyons for resolution.
If the mail the program is sending is associated with a LISTSERV or Mailman list, the owner(s) or administrator(s) of that list might fit the first or second categories listed above. In that case, a generic way to refer to them would be OWNER-<listname>@LISTSERV.MIT.EDU (for a LISTSERV list) or <listname>-OWNER@MIT.EDU (for a Mailman list).

Intercepting and Logging E-mail via Z_SENDMAIL

Each call to the custom function module Z_SENDMAIL must pass a two-character "E-Mail Handling Category" in the P_HNCAT parameter (see previous section). The ZEHCAT table is used in conjunction with this e-mail handling category to instruct Z_SENDMAIL to intercept and/or log the e-mail message.

The purpose of documents listed below is to:
 


          View document : Intercepting and Logging E-mail via Z_SENDMAIL

          View documentE-mail Handling Categories

Restricting the Capabilities of Select-Options in ABAP Programs

The following document discusses how to restrict the capabilities of select-options in an ABAP
program. In particular, it addresses the special situation of restricting a select-option in a
program that makes use of the standard MES include file ZES_AFTER_INIT_FOR_S_BUKRS
(this include file already contains code to restrict the company code select-option, S_BUKRS).

View Document :  Restricting_Select_Options

Table of Enterprise Structure Attributes

In the original SAP implementation at MIT, we had written all our custom programs assuming that there was only one company code, one controlling area, one currency, one fiscal year variant, etc. When a decision was made to alter our configuration to have multiple company codes, controlling areas, and fiscal year variants, we had to review all our custom code and modify more than half of it to accommodate multiple enterprise structures. We wanted to protect ourselves from ever having to go through that experience again. We created an "MES Toolkit" consisting of three function modules, about nine include files, and cookbook documentation describing how to use them. One of benefits of the "MES Toolkit" is that it provides structures that contain all the relevant MES variables so that (after it has been initialized properly) they can be used like SY-* variables Ð there is a consistent set of names that will be populated with the correct values and be referred to in a consistent way in all programs (that use the "MES Toolkit"). We defined 7 different MES compliance levels (depending on what the program had to do) and we added a command to the ABAP editor for recording a programÕs MES compliance level. We also have a required field when submitting a transport request (via ZUTTREQ) to state the MES compliance of the program being transported. We wanted to be sure that all new programs and every program that was modified in a way dealing with multiple enterprise attributes followed these procedures - to save us the effort of ever going to go through the conversion again.

All new programs, all programs that undergo significant modification or enhancement, and every program that was modified in a way dealing with multiple enterprise attributes must be written to function correctly in an environment where we may have many different enterprise structures in the same SAP client - preferably by using the "MES Toolkit".

The 7 different MES compliance levels:
1 Supports only company 'CUR' (and therefore CO area 'MIT')
2 Supports any one user-specified company in the 'MIT' controlling area
3 Supports any one user-specified company in any one user-specified controlling area
4 Supports any user-specified group of companies in the 'MIT' controlling area
5 Supports any user-specified group of companies in any one user-specified controlling area
6 Program doesn't filter by company code (i.e. it processes all companies)
7 Supports any user-specified group of companies which may span more than one controlling area

The following table lists those enterprise structure attributes that have thus far been identified as those whose value should be determined dynamically.  That is, they should not be assumed to have a constant value throughout the SAP system, but instead, should be derived either through user input or via table lookups based upon the value of a known related attribute.
      Area         Attribute Par ID   Valid Values  Campus Value   Typical Use
Cross Application Fiscal Year Variant GJVAR T009-PERIV V6  (see table T009 in Production) MARC-PERIV
Cross Application Chart of Accounts  KPL T004-KTOPL   HEUS SKA1-KTOPL
Cross Application Country LND T005-LAND1 US CSKS-LAND1
Cross Application Currency  (used as transaction currency)  FWS TCURC-WAERS USD BKPF-WAERS
Cross Application Currency  (used as company code currency) FWS TCURC-WAERS USD GLT0-HSL01
Cross Application Currency  (used as CO area currency) FWS TCURC-WAERS USD COSS-WKG001
Cross Application Currency  (used as group currency) FWS TCURC-WAERS USD GLT0-KSL01
Finance Consolidation Company GCC  T880-RCOMP MIT   GLT2-RCOMP
Finance Company Code BUK T001-BUKRS CUR CSKS-BUKRS
Finance Funds Mgmt Area FIK FM01-FIKRS  MIT FMFCTR-FIKRS
Finance Credit Control Area KKB T014-KKBER MIT1 BSEG-KKBER
Finance  Business Area  GSB  TGSB-GSBER  <initial>(Not currently used) BSEG-GSBER
Finance Functional Area  FBE TFKB-FKBER  <initial>(Not currently used)  BSEG-FKBER
Controlling  Controlling Area  CAC TKA01-KOKRS  MIT CSKS-KOKRS
Sales and Distribution Sales Organization VKO  TVKO-VKORG  Several  (see table TVKO in Production) VBAK-VKORG
Sales and Distribution Distribution Channel  VTW  TVTW-VTWEG 10 VBAK-VTWEG
Sales and Distribution  Division  SPA  TSPA-SPART  10 VBAK-SPART
Materials Management  Plant WRK T001W-WERKS Several  (see table T001W in Production)  EBAN-WERKS
Materials Management Purchasing Organization   EKO  T024E-EKORG GPO, SUB EKKO-EKORG
Human Resources  Personnel Area  PBA  T500P-PERSA  Several  (see table T500P in Production)  PA0001-WERKS
Human Resources  Personnel Sub-Area  PBS T001P-BTRTL  Several  (see table T001P in Production)  PA0001-BTRTL

The values of most enterprise structure attributes may be derived from the value of some "base" attribute such as company code or controlling area.  Therefore, many programs will not require that their selection screens contain any enterprise structure attributes other than company code and controlling area.

The program should be written so that it uses variables containing the values of enterprise structure attributes obtained from the selection screen and system tables, even in the event that the program may not permit user entry of the "base" attributes and hence only one set of values will be used for the enterprise structure attributes.

The M.E.S. (Multiple Enterprise Structure) include files described in the next sectiuon automatically gather some of these enterprise structure variables for you.  The M.E.S. function modules can also be used to gather values in a standard way.

In an effort to assist developers in making MIT custom programs MES (multiple enterprise structure) compliant, numerous standard INCLUDE programs and function modules have been developed.  The following section describes the use of these standard routines when developing a list-processing program.

General Toolkit for Multiple Enterprise Structures

Directions in this section will support one or more (user-specified or defaulted) companies in a (user-specified or defaulted) controlling area. It involves the use of a parameter to indicate the chosen controlling area and includes variations to allow either a parameter or a select-option for indicating the chosen company code(s).

I. What you must include near the beginning of the program:

    A. In the case where the program selects company codes via a select-option, you must add
        the following statement within the section where you are declaring database tables
        (unless GLPCA is already in a TABLES statement):

      TABLES GLPCA.

    B. Early in the section where you are declaring global data, include:

      INCLUDE ZES_GLOBAL_DATA_ALWAYS.

    C. Controlling area: Include a parameter named A_KOKRS in the definition of the selection screen
         and create the selection text "Controlling Area" for it:

            1. If the user can NOT choose a controlling area (i.e., this program only works for
                companies in controlling area "MIT"), include in the definition of  the selection
                screen (but users will NOT see it):

     PARAMETERS: A_KOKRS LIKE GLPCA-KOKRS NO-DISPLAY DEFAULT 'MIT'.

            2. If the program will work for any company code(s) in any controlling area but the user is
                supposed to make the selection by company code, include in the definition of the selection
                screen (but users will NOT see it):

      PARAMETERS: A_KOKRS LIKE GLPCA-KOKRS NO-DISPLAY.

            3. If the user CAN choose a controlling area, but the user must explicitly select it (rather
                than allowing the program to deduce it from the company code(s)), include in the
                definition of the selection screen:

     PARAMETERS: A_KOKRS LIKE GLPCA-KOKRS OBLIGATORY MEMORY ID CAC

            4. If the user CAN choose a controlling area and the user MAY also leave it blank (to
               allow the program to deduce it from the company code(s)), include in the definition
               of the selection screen:

      PARAMETERS: A_KOKRS LIKE GLPCA-KOKRS MEMORY ID CAC.

    D. Company code: Include either a parameter named A_BUKRS or a Select-Option named
      S_BUKRS in the definition of the selection screen. If the user is allowed to select more
         than one company code, clearly, the select-option must be used.  If only one company
         code may be selected, either approach is allowed.  Whether a parameter or select-option
         is used, you must create a selection text "Company Code" for it.

            1. If the user can NOT choose a company code (i.e., this is a program which only works for
                company code "CUR"), include in the definition of the selection screen (but users will NOT
                see it) either:

             SELECT-OPTIONS:   S_BUKRS FOR GLPCA-RBUKRS
                          NO INTERVALS NO-EXTENSION
                          NO-DISPLAY DEFAULT 'CUR'.
        or:

        PARAMETERS:       A_BUKRS LIKE GLPCA-RBUKRS
                          NO INTERVALS NO-EXTENSION
                          NO-DISPLAY DEFAULT 'CUR'.

            2. If the user CAN choose exactly one company code, include in the definition of the
                selection screen either:

        SELECT-OPTIONS:   S_BUKRS FOR GLPCA-RBUKRS
                          NO INTERVALS NO-EXTENSION
                          OBLIGATORY MEMORY ID BUK.

        or:

        PARAMETERS:       A_BUKRS LIKE GLPCA-RBUKRS
                          NO INTERVALS NO-EXTENSION
                          OBLIGATORY MEMORY ID BUK.

            3. If the user CAN choose one or more company codes, include in the definition of the
                selection screen:

        SELECT-OPTIONS:   S_BUKRS FOR GLPCA-RBUKRS
                          NO INTERVALS MEMORY ID BUK.

    E. Early in the INITIALIZATION event, include the following line:

              INCLUDE ZES_AFTER_INIT_ALWAYS.

               Additionally, if you are using the select-option, S_BUKRS, include the line:

               INCLUDE ZES_AFTER_INIT_FOR_S_BUKRS.

    F. In the part of the program where you have AT SELECTION-SCREEN events, you must include
        two ABAP statements. Please note that each of these statements declares the beginning of
        an event (for example,. "AT SELECTION-SCREEN ON A_KOKRS"). The second of them
        should be immediately followed by another event.

        The first of the two statements is:

              INCLUDE ZES_AT_SEL_SCREEN_ON_A_KOKRS.

        If the parameter, A_BUKRS, is used to select company code, the second statement must be:

          INCLUDE ZES_AT_SEL_SCREEN_ON_A_BUKRS.

        Otherwise (i.e. S_BUKRS was used) the second statement must read:

              INCLUDE ZES_AT_SEL_SCREEN_ON_S_BUKRS .

    G. Early in the START-OF-SELECTION event, one line must be included.  If the parameter,
         A_BUKRS, is used to select company code, this statement must read

              INCLUDE ZES_AFTER_S_O_SEL_FOR_A_BUKRS.

        Otherwise, (i.e. S_BUKRS was used) the statement must read:

          INCLUDE ZES_AFTER_S_O_SEL_FOR_S_BUKRS.
 

II. What is available for your use:

        A.  After the ZES_AFTER_S_O_SEL_FOR_A_BUKRS or
       ZES_AFTER_S_O_SEL_FOR_S_BUKRS  include, the following
      COMMON_ESA- variables and R_ES_ range tables are automatically defined and
             set to appropriate values. If more than one company code was supplied (or implied),
             the COMMON_ESA- variables are set to the appropriate value only if it is common
             to all the company codes - otherwise the COMMON_ESA- variable is left blank.
             (Hence, if only one company code was supplied (or implied) you get some
             additional values.)

            1. Variables set when more than one company code is supplied (or implied):

           Controlling Area           COMMON_ESA-KOKRS (like TKA01-KOKRS)
       Fiscal Year Variant        COMMON_ESA-PERIV (like T009-PERIV)
       Chart of Accounts          COMMON_ESA-KTOPL (like T004-KTOPL)
       Currency                   COMMON_ESA-WAERS (like TCURC-WAERS)
       Consolidation Company      COMMON_ESA-RCOMP (like T001-RCOMP)
       Funds Management Area      COMMON_ESA-FIKRS (like FM01-FIKRS)
       Default Credit Ctrl Area   COMMON_ESA-KKBER (like T014-KKBER)

            2. Additional variables which MAY be set when more than one company code is supplied and
                WILL be set when only one company code is supplied (or implied):

        Country                    COMMON_ESA-LAND1 (like T005-LAND1)

            3. Additional variables set when only one company code is supplied (or implied):

           Company Code              SINGLE_ESA-BUKRS (like T001-BUKRS)
       Company Name (25 chars)   SINGLE_ESA-BUTXT (like T001-BUTXT)
       Company Name (40 chars)   SINGLE_ESA-BUKRS_NAME1
       (like ADRC-NAME1)

            4. Range tables: If more than one company code was supplied (or implied), the  R_ES Range
                    tables are filled with the union of the values from all the company codes.

        Company Code             R_ES_BUKRS       (like RANGE_BUKRS_CO)
       Sales Organizations      R_ES_VKORG       (like SHP_VKORG_RANGE)
       Distribution Channels    R_ES_VTWEG       (like SHP_VTWEG_RANGE)
       Divisions                R_ES_SPART       (like SHP_SPART_RANGE)
       Plants                   R_ES_WERKS       (like RANGE_WERKS)
       Purchasing Organizations R_ES_EKORG       (like EKORG_RANG)
       Personnel Areas          R_ES_PERSA       (like RANGE_C4)
       Personnel Sub-areas      R_ES_BTRTL       (like RANGE_C4)

        B. New function modules - Three new function modules are being provided. Two of them are
             automatically called in the above include files and the results are left in the above variables
             and range tables for your use.

                1. A function module named Z_ES_GET_ENTERPRISE_ATTRIBUTES which
                    returns other enterprise attributes that can be deduced from the ones that you
                    supply in the call.
                2. A function module named Z_ES_GET_ESA_RANGES which returns range tables filled
                    with the values associated with the company/ies that you supply in the call.
                3. A function module named Z_ES_GET_COMP_CODE_ATTRIBUTES that calls the
                    above two function modules. This function module provides a slightly simpler
                    interface when you are dealing with exactly one company at a time.

        C. Company code associated with a cost object: The table ZCOOBJECT has been expanded to
             include the company code associated with each cost object. Two existing MIT-written
             function modules have been modified to return the company code associated with a cost
             object, if the caller requests it. They are:

              1. Z_GET_COST_OBJECT
          2. Z_CO_GET_COST_OBJECT_TYPE

        D. Accessing some of the enterprise attributes:

                1. If you want to know how many companies were selected, you can use the following:

              DATA NUMBER_OF_COMPANIES TYPE I.
          DESCRIBE TABLE R_ES_BUKRS LINES NUMBER_OF_COMPANIES.

                2. If you want to get the enterprise attributes for particular companies, one company at
                    a time, get the company codes from  R_ES_BUKRS-LOW   and call
                    Z_ES_GET_ENTERPRISE_ATTRIBUTES for each one. The structure
                    SINGLE_ESA is a convenient place to hold the results.
                    Your code might look something like this:

         LOOP AT R_ES_BUKRS.

                        "Execute the body of this loop once for each company
                        *  If you need some enterprise attribute values associated with this company
                        *  that are not "common" enterprise attribute values across multiple companies

            CALL FUNCTION 'Z_ES_GET_ENTERPRISE_ATTRIBUTES'
            EXPORTING
              I_BUKRS  = R_ES_BUKRS-LOW
            IMPORTING
              E_PERIV  = SINGLE_ESA-PERIV
              E_KTOPL  = SINGLE_ESA-KTOPL
              E_WAERS  = SINGLE_ESA-WAERS
              E_LAND1  = SINGLE_ESA-LAND1
              E_RCOMP  = SINGLE_ESA-RCOMP
              E_BUKRS  = SINGLE_ESA-BUKRS
              E_FIKRS  = SINGLE_ESA-FIKRS
              E_KKBER  = SINGLE_ESA-KKBER
              E_KOKRS  = SINGLE_ESA-KOKRS
              E_BUTXT  = SINGLE_ESA-BUTXT
              E_BUKRS_NAME1 = SINGLE_ESA-BUKRS_NAME1
            EXCEPTIONS
              CANNOT_FIND_ALL_REQUESTED_DATA = 1
              OTHERS     = 2.

            IF SY-SUBRC <> 0.
              MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
              WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
            ENDIF.

                        As a result of the include files, the R_ES_ range tables are set with the "union" of the
                        values for all the selected companies. If that is appropriate for your program, don"t
                        call Z_ES_GET_ESA_RANGES. If you need range tables associated with one
                        company at a time, you can call the function module Z_ES_GET_ESA_RANGES.
                        If you need range tables associated with one company at a time but you don"t need
                        the "union" range tables, you can overwrite them, as we do in the following code.
                        If you need both the "union" range tables and company-specific range tables, you
                        can store the results in new tables that you defined to be LIKE the R_ES_ tables.

             CALL FUNCTION 'Z_ES_GET_ESA_RANGES'
              EXPORTING
                I_BUKRS  = R_ES_BUKRS-LOW
              TABLES
                R_PERIV  = R_ES_PERIV
                R_KTOPL  = R_ES_KTOPL
                R_WAERS  = R_ES_WAERS
                R_LAND1  = R_ES_LAND1
                R_RCOMP  = R_ES_RCOMP
                R_FIKRS  = R_ES_FIKRS
                R_KKBER  = R_ES_KKBER
                R_GSBER  = R_ES_GSBER
                R_KOKRS  = R_ES_KOKRS
                R_VKORG  = R_ES_VKORG
                R_VTWEG  = R_ES_VTWEG
                R_SPART  = R_ES_SPART
                R_WERKS  = R_ES_WERKS
                R_EKORG  = R_ES_EKORG
                R_PERSA  = R_ES_PERSA
                R_BTRTL  = R_ES_BTRTL
              EXCEPTIONS
                INPUT_PARAMETERS_MISSING = 1
                TOO_MANY_INPUT_PARAMETERS = 2
                OTHERS     = 3.

              IF SY-SUBRC <> 0.
                MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
                WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
              ENDIF.

                            Do the program logic needed for this company here.   The enterprise attributes
                            are in the SINGLE_ESA structure.  If you called Z_ES_GET_ESA_RANGES, you
                            have range table for this company. If you didn"t call Z_ES_GET_ESA_RANGES,
                            you have the range tables for the union of all selected companies.

         ENDLOOP.

III. Other Aspects to Consider:
      The full scope of what else needs to be done will depend on what the program
      is trying to do, which tables it uses and how it uses them.
      For example, if the program uses custom tables, the programmer will have to decide whether
      any enterprise attributes need to be added to those tables (and if so, which attributes).

      A. Use values from the SINGLE_ESA  or  COMMON_ESA structures rather than literals or
          constant for the values of enterprise structure attributes. (This is necessary to make
          a program work for a user-specified company. If you are just making a program work
          for one program-specified company code, it is very desirable, but not strictly necessary,
          to use values from the SINGLE_ESA or COMMON_ESA structures rather than literals or
          constants for the values of enterprise structure attributes.) Note that programs should
          NOT refer to A_KOKRS, A_BUKRS, or S_BUKRS (other than setting up the selection
          screen as described in the first section of this document).  Programs should instead
          refer to SINGLE_ESA-KOKRS, SINGLE_ESA-BUKRS, or R_ES_BUKRS.

     B. In the WHERE clause of SELECT statements, use the appropriate SINGLE_ESA-variable,
          COMMON_ESA-variable or R_ES_ range table to restrict the data to the company/ies with
          which the program is supposed to work. Even if a program is only being made to work with
          one program-selected company code, the WHERE clause must still restrict the data being
          retrieved. In this case, it is very desirable, but not strictly necessary, to use the
          SINGLE_ESA-variable, the COMMON_ESA-variable or the R_ES_ range tables
          for this purpose.

      C. Some programs operate on an externally supplied list of cost objects, documents, or other
          master or transactional data objects. For example, such an external list might be supplied
          via an input file, a spreadsheet upload, or a selection screen. The program should  verify
          that all these externally supplied data objects are associated with the company/ies with
          which the program is supposed to be working.

          In the case of cost objects, that means call either the Z_GET_COST_OBJECT or
            Z_CO_GET_COST_OBJECT_TYPE function module for each externally supplied cost object
          and verify that "BUKRS EQ SINGLE_ESA-BUKRS" (or, more generally,
          "BUKRS IN R_ES_BUKRS"). How the test should be done for other types of data objects,
          depends on the data object. The test should be done using the SINGLE_ESA- variables,
          COMMON_ESA- variables and R_ES_ range tables, so as to make the program easy to
          maintain and extend to other companies or groups of companies.

      D. Most output should show which company it is for. For an internal report, you might just show
           in the header of the report the company code(s) whose data is included. Any business
          document (for example, a Purchase Order or Invoice) which will go to another party should
          show the name of the company from which it was generated. (The variables
          SINGLE_ESA-BUTXT and SINGLE_ESA-BUKRS_NAME1 are 25 and 40 character (respectively)
          fields for the company name.)

      E. Make sure that the correct monetary fields are used. For FI tables, use the monetary amount
          in the company code currency field, sometimes described as the "local currency" field.
          Generally, it is NOT the monetary amount in the field described as "document currency" or
          "transaction currency".   For CO tables, use the monetary amount in the controlling area
          currency field.  For more information, see the section of this document called
      "Choice of Currency Fields".

      F. Determining the relationship between calendar months and fiscal periods: This is not strictly
            necessary for programs that only handle  companies in the "MIT" controlling area, but it is
            a good programming practice. (In addition to the specific function modules cited
            here, other function  modules in the function groups ADAT and FACS may be helpful,
           depending on the situation.)

                1. To convert a calendar date to a fiscal year and period, use function module
                         DATE_TO_PERIOD_CONVERT
                    (or function module FI_PERIOD_DETERMINE).
                2. To convert fiscal year and period to the calendar date of the first day of the period,
                    use function module FIRST_DAY_IN_PERIOD_GET.
                3. To convert fiscal year and period to the calendar date of the last day of the period,
                    use function module LAST_DAY_IN_PERIOD_GET.

 

Uploading and Downloading files between the SAPgui & the R/3 System

In R/3 4.6C, ABAP programs should use the WS_UPLOAD and WS_DOWNLOAD
function modules (rather than the GUI_UPLOAD and GUI_DOWNLOAD function
modules or static methods).

In R/3 6.20 and later, the WS_UPLOAD and WS_DOWNLOAD function modules
are still available, but the GUI_UPLOAD and GUI_DOWNLOAD static
methods of the CL_GUI_FRONTEND_SERVICES class are preferred. New code
that will not be used until after our SAP upgrade should use the
GUI_UPLOAD and GUI_DOWNLOAD static methods of the

GUI : SAP Style Guide


CL_GUI_FRONTEND_SERVICES class (rather than the WS_UPLOAD and
WS_DOWNLOAD function modules).



 

V.  USER INTERFACE STANDARDS

For applications that require dialog programming, the SAP Style Guide should be used as a basis for development. Using this guide for screen design and ergonomics will insure consistency in MIT developed transactions. The SAP Style Guide is available in the help documentation using the following path:  Help -> R/3 Library -> BC-Basis Components -> ABAP Workbench (BC-DWB) -> BC-> SAP Style Guide. Another useful resource is the SAP supplied demo transaction which gives examples (with documentaion) of the standards used in both dialog programming and list generation. The demo transaction BIBS is used for screen painter guidelines. The demo transaction LIBS is used for list output guidelines.

GUI : Screen Painter Resolution

The MIT user community, in general, uses monitors capable of at least 800x600 resolution. Hence, any screen painter development should ensure that all fields are viewable within that screen size. This corresponds to the SAP default screen size of 21 lines by 83 columns. Note that SAP does not include the title, menu bar, status line, and OKCode box in this area.

MIT-ITS Web Site Look and Feel Standards

View Document: MIT-ITS Web Site Standards

Radio Button Groups: Use a default to avoid unexpected results

Radio Button Groups:

In each radio button group exactly one button in the radio button group must be defaulted to 'X'.

Example:

parameter: p_rb1 radiobutton group grp1 default 'X',
                p_rb2 radiobutton group grp1.

If we did not have the above requirement, and no radio button was defaulted to 'X', then we would get different behavior when the program was run interactively versus being run in the background(when run in the background, no radio button would be set.  When run interactively, the first radio button would be set.)


 

VI. DOCUMENTATION STANDARDS


Configuration Documentation

FI Document Types (includes AP, GL, MM)

Accounting document type configuration is maintained as part of the SAP configuration process. As such, you must always confirm any new document types with the configuration team prior to coding a report to access the data.

Also, existing extract programs may need to be modified for the new document type, hence it is necessary to pro-actively notify The Financial Architecture Group < sap-doc-types@mit.edu > of the creation of a new document type. After the new document type is approved, the Financial Architecture Group will communicate the changes to all other necessary parties so that other programs can be modified.

Source Code Documentation

ABAP/4 code is fairly self-documenting. However, it is wise to provide future programmers with documentation. Explain the purpose, design, structure and any testing hints at the top of the program. Maintain a history of modification notes, dated, with the most recent change first. Comment work fields, and fields in work records especially those used for interfacing. Comment all subroutines with their purpose. Comments should explain what the code is doing, not how the code is doing it.

MIT has developed several templates for providing documentation via the ABAP "Program Documentation" function. From the ABAP Editor transaction SE38, you can access the documentation by selecting object component "Documentation" then click "Display", or from within the editor screen by doing Goto -> Program doc. The MIT templates are in the following ABAP programs:
Program
Usage
ZPROGDOC
ABAP/4 Program documentation
ZSYSTDOC
System documentation
ZFUNCDOC
Function Module documentation
ZINCLDOC
Include documentation
ZRPRPDOC
Report Painter report documentation

Note that a "general purpose" include file, or any include file which is not documented in the documentation for an associated main program, should be documented using the "program" template (ZPROGDOC) rather than the degenerate "include file" template (ZINCLDOC). There must be documentation for the code within an include file either in the include file documentation itself (using the long form contained in ZPROGDOC), or in the main program's documentation object (ZPROGDOC). In the case of the latter, the short form contained in ZINCLDOC must be filled out with information which points to the main program.

It is mandatory to complete a documentation template prior to transporting your program to the production system.

In addition to documentation via the templates, brief comments within the code can be very helpful for ongoing program maintenance.  For example, you should document the major steps in the program source, such as:

  do 16 times.  "why are we doing this 16 times instead of 12???
   ...
  enddo.

 For the example of CASE statements, each case value should be documented:

   case <variable>.

    when 'Y'.  "explain what 'Y' actually means
      ...
    when 'H'.  "explain what 'H' actually means
      ...
  endcase.

When modifying a program, to document within the source code, you can use the following convention:
 
*-----------------------------------------------------------------*
* This program is Multiple Enterprise Structure compliant
* at level 4.
* It runs for any selected company code(s) in the MIT "CO" area.
*
* Purpose:
*
*
*-----------------------------------------------------------------*
* Author:
* Date:
*
*-----------------------------------------------------------------*
* Revision History:
*
*   Date     Author      Transport/Description
* --------- ---------    ----------------------
* 13-Nov-01  John Doe    SF2K123456
*          1. This is the documentation of one of the revisions 
*             made within transport SF2K123456.
*          2. This is the doumentation of a different revision
*             revision made within transport SF2K123456.
*          3. This is the documentation for yet another revision
*             made within the same transport.
* 06-Jun-00  Jane Doe     SF2K012345
*          1. This is the documentation for a revision within
*             transport SF2K012345
*-----------------------------------------------------------------*

     DATA: BEGIN OF rec,                          "SF2K900001

        ind,                                 "interface type ind.
        f1 LIKE MA-IDNRA,                    "material number
        f2 LIKE MA-KTX01,                    "material short text
        f3(16),            "filler           "SF2K9000000
        ...

     END OF rec.

This convention is available from the ABAP editor, via the pattern function. Select "DOCU_BLOCK" from the "other pattern" option to paste it into your program.

Always indicate which lines were changed or added by appending the transport (change request) number to the line. (This is the convention used by SAP developers).
 
INSERT D030L-TYPE D030L-DDNAME D030T-DDTEXT D030L-CBNAME
       D030L-SEGMENTID D030L-DOCTYPE INTO HEADER.

SELECT * FROM D030L WHERE                       "SF2K900001
         DDNAME BETWEEN TABLEFR AND TABLETO. 

  CHECK D030L-DDMODIFY NE USR. 

  SELECT * FROM

Validation Rules

D030T WHERE 

    DDLANGUAGE EQ SY-LANGU AND
    DDNAME EQ D030L-DDNAME.

  ENDSELECT. 

  EXTRACT HEADER. 

ENDSELECT. 

Function Modules

The import and export parameters of function modules should have names beginning with 'I_' and 'E_' respectively. They should be documented with brief descriptions of the fields and their typical contents. Also, any special requirements or usage should be noted. At the minimum, the documentation 'Short Text' should be completed for each parameter. This is found by selecting the 'interface' radio button on the main function module transaction, SE37. From there, click on the 'Documentation' tab.

Because of the nature of the impact of changes in validation rules to the entire SAP system operation, validation rules should only be changed by (or with the permission of) the Validation Rules Team. If you need a new or modified validation rule, do not act unilaterally, instead coordinate with the Validation Rules Team. Any developer who is considering altering a validation rule must send a message to MIT-ABAP@MITVMA.MIT.EDU as early in the development process as possible.  At a minimum this notification must be sent one week before any development is transported to the test and integration system (SF5).

Configuration Changes that alter Transaction Fields

As with changes to validation rules, any configuration changes that alter the "required", "optional", or "not permitted" status of fields, or that remove a field, must be submitted in a mail message to MIT-ABAP@MITVMA.MIT.EDU as early as possible with a minimum of one week notification before transport to the test and integration system.


 

VII. PERFORMANCE STANDARDS

General Performance Standards

   
1. "Dead" code

Avoid leaving "dead" code in the program. Comment out (or delete) variables that are not referenced and code that is not executed. Use program --> check --> extended program check to see a list of variables which are not referenced statically
2. Use logical databases

Choose the most efficient logical data base possible. Study the selection criteria and which secondary indexes are used for that view. Provide the appropriate selection criteria to limit the number of data base reads. Force users to provide selection criteria by evaluating the selection criteria entered on the selection screen during the AT SELECTION-SCREEN event. Finally, when possible take advantage of the matchcodes to increase speed
3. Subroutine usage

For good modularization, the decision of whether or not to execute a subroutine should be made before the subroutine is called. For example:

This is better:
IF f1 NE 0.

  PERFORM sub1.

ENDIF.

FORM sub1.
  ... 
ENDFORM.

Than this:

PERFORM sub1.

FORM sub1.
  IF f1 NE 0.
    ... 
  ENDIF.

ENDFORM.
 

4. IF statements

When coding IF tests, nest the testing conditions so that the outer conditions are those which are most likely to fail. For logical expressions with AND , place the mostly likely false first and for the OR, place the mostly likely true first.

Example - nested IF's:

  IF (least likely to be true).

    IF (less likely to be true).

     IF (most likely to be true).
     ENDIF.
    ENDIF.
   ENDIF.

Example - IF...ELSEIF...ENDIF :

  IF (most likely to be true).

  ELSEIF (less likely to be true).

  ELSEIF (least likely to be true).

  ENDIF.

Example - AND:

   IF (least likely to be true) AND 
      (most likely to be true).

   ENDIF.

Example - OR:

        IF (most likely to be true) OR
      (least likely to be true).
 

5. CASE vs. nested IFs

When testing fields "equal to" something, one can use either the nested IF or the CASE statement. The CASE is better for two reasons. It is easier to read and after about five nested IFs the performance of the CASE is more efficient.
6. MOVE-ing structures

When records a and b have the exact same structure, it is more efficient to MOVE a TO b than to  MOVE-CORRESPONDING a TO b.

 MOVE BSEG TO *BSEG.

is better than

 MOVE-CORRESPONDING BSEG TO *BSEG.
 

7. SELECT and SELECT SINGLE

When using the SELECT statement, study the key and always provide as much of the left-most part of the key as possible. If the entire key can be qualified, code a SELECT SINGLE not just a SELECT.   If you are only interested in the first row or there is only one row to be returned, using SELECT SINGLE can increase performance by up to three times.
8. Small internal tables vs. complete internal tables

In general it is better to minimize the number of fields declared in an internal table.  While it may be convenient to declare an internal table using the LIKE command, in most cases, programs will not use all fields in the SAP standard table.  For example:

Instead of this:

data:  t_vbak like vbak occurs 0 with header line.

Use this:

data: begin of t_vbak occurs 0,

        vbeln like vbak-vbeln,
        ...
        end of t_vbak.
 

9. Row-level processing of a table

Selecting data into an internal table using an array fetch versus a SELECT-ENDELECT loop will give at least a 2x performance improvement.  After the data has been put into the internal table, then row-level processing can be done. 
For example, 
   use:

select ... from table <..>
into <itab> (corresponding fields of itab)
where ...
 

loop at <itab>
<do the row-level processing here>
endloop.
   instead of using:
 

select ... from table <...
where ...
<row-level processing>
append <itab>.
endselect.
 

10. Row-level processing and SELECT SINGLE

Similar to the processing of a SELECT-ENDSELECT loop, when calling multiple SELECT-SINGLE commands on a non-buffered table (check Data Dictionary -> Technical Info), you should do the following to improve performance: 
  • Use the SELECT into <itab> to buffer the necessary rows in an internal table, then
  • sort the rows by the key fields, then 
  • use a READ TABLE WITH KEY ... BINARY SEARCH in place of the SELECT SINGLE command. Note that this only make sense when the table you are buffering is not too large (this decision must be made on a case by case basis).
11. READing single records of internal tables

When reading a single record in an internal table, the READ TABLE WITH KEY is not a direct READ.  This means that if the data is not sorted according to the key, the system must sequentially read the table.   Therefore, you should:
  • SORT the table
  • use READ TABLE WITH KEY BINARY SEARCH for better performance.
12. SORTing internal tables

When SORTing internal tables, specify the fields to SORTed.

SORT ITAB BY FLD1 FLD2.

 is more efficient than

SORT ITAB.
 

13. Number of entries in an internal table

To find out how many entries are in an internal table use DESCRIBE.

DESCRIBE TABLE ITAB LINES CNTLNS.

 is more efficient than

LOOP AT ITAB.

  CNTLNS = CNTLNS + 1.

ENDLOOP.
 

14. Length of a field

To find out the length of a field use the string length function.

FLDLEN = STRLEN (FLD).

 is more efficient than

IF FLD CP '* #'.

ENDIF.

FLDLEN = SY-FDPOS.
 

15. Performance diagnosis

To diagnose performance problems, it is recommended to use the SAP transaction SE30, ABAP/4 Runtime Analysis. The utility allows statistical analysis of transactions and programs.
16. Nested SELECTs versus table views

Since releASE 4.0, OPEN SQL allows both inner and outer table joins.  A nested SELECT loop may be used to accomplish the same concept.  However, the performance of nested SELECT loops is very poor in comparison to a join.  Hence, to improve performance by a factor of 25x and reduce network load, you should either create a view in the data dictionary then use this view to select data, or code the select using a join.
17. If nested SELECTs must be used

As mentioned previously, performance can be dramatically improved by using views instead of nested SELECTs, however, if this is not possible, then the following example of using an internal table in a nested SELECT can also improve performance by a factor of 5x:

Use this:
form select_good.

  data: t_vbak like vbak occurs 0 with header line.
  data: t_vbap like vbap occurs 0 with header line.

  select * from vbak into table t_vbak up to 200 rows.
  select * from vbap 
          for all entries in t_vbak
          where vbeln = t_vbak-vbeln.
    ...
  endselect.

endform.

Instead of this:
form select_bad.

 select * from vbak up to 200 rows.

  select * from vbap where vbeln = vbak-vbeln.
      ...
  endselect.

 endselect.

endform.

Although using "SELECT...FOR ALL ENTRIES IN..." is generally very fast, you should be aware of the three pitfalls of using it:

Firstly, SAP automatically removes any duplicates from the rest of the retrieved records.  Therefore, if you wish to ensure that no qualifying records are discarded, the field list of the inner SELECT must be designed to ensure the retrieved records will contain no duplicates (normally, this would mean including in the list of retrieved fields all of those fields that comprise that table's primary key).

Secondly,  if you were able to code "SELECT ... FROM <database table> FOR ALL ENTRIES IN TABLE <itab>" and the internal table <itab> is empty, then all rows from <database table> will be retrieved.

Thirdly, if the internal table supplying the selection criteria (i.e. internal table <itab> in the example "...FOR ALL ENTRIES IN TABLE <itab> ") contains a large number of entries, performance degradation may occur.
 

18. SELECT * versus SELECTing individual fields

In general, use a SELECT statement specifying a list of fields instead of a SELECT * to reduce network traffic and improve performance.  For tables with only a few fields the improvements may be minor, but many SAP tables contain more than 50 fields when the program needs only a few.  In the latter case, the performace gains can be substantial.  For example:

Use:

select vbeln auart vbtyp from table vbak

  into (vbak-vbeln, vbak-auart, vbak-vbtyp)

  where ...

Instead of using:

select * from vbak where ...
 

19. Avoid unnecessary statements

There are a few cases where one command is better than two.  For example:

Use:

append <tab_wa> to <tab>.

Instead of:

<tab> = <tab_wa>.

append <tab> (modify <tab>).

And also, use:

if not <tab>[] is initial.

Instead of:

describe table <tab> lines <line_counter>.

if <line_counter> > 0.
 

20. Copying or appending internal tables

Use this: 

<tab2>[] = <tab1>[].  (if <tab2> is empty)

Instead of this:

loop at <tab1>.

  append <tab1> to <tab2>.

endloop.

However, if <tab2> is not empty and should not be overwritten, then use:

append lines of <tab1> [from index1] [to index2] to <tab2>.
 

21. Declaring Internal Tables using R/3 Release 4.x syntax

R/3 release 4.6 contains capabilities for hashing and sorting internal tables that improve system performance.   The 4.6 syntax should be used whenever coding internal tables.  The following examples illustrate the use of this syntax. 

    * First,declare the header line or work area (wa) as a type:

      TYPES: begin of <line_type>,
             field1 like ...,
             ....
             fieldn like ..,
             end of <line_type>.

     * For example, here is a table line type with some vendor fields

      TYPES:  Begin of TY_VENDOR_DATA,
               LIFNR type LFA1-LIFNR,
               NAME1 type LFA1-NAME1,
             End of TY_VENDOR_DATA. 

      or

      TYPES: <line_type> like <DD table or DDstructure>.

  * This version would include ALL of the vendor (LFA1) fields

      TYPES:  TY_VENDOR_DATA TYPE LFA1.

      You may then declare the internal  table (see Below) or, optionally, you may first
            declare a table type.  Declaring a table type would be preferable in those cases
            where your program declares several internal tables of the same type (and
            therefore the table type can be reused by each internal table declaration)
            or where the internal table is passed to subroutines or methods (and therefore
            the table type can be included in the form/method interface definition.

      TYPES: <t_table_type> type <line_type> occurs 0.

  * This example would define a standard (i.e. unsorted) table type

      TYPES: ty_t_vendor type ty_vendor_data occurs 0.

      or

      TYPES: <t_table_type> type
             [sorted|hashed|standard|index|any]
             table of <line_type> 
             with [unique|non-unique] key <key definition>].

  * This example would define a vendor table type sorted by vendor number
 

     TYPES: ty_t_vendor type sorted table of ty_vendor_data
           with unique key lifnr.

       * Finally declare the table and the work area:

     DATA:<t_table> type <t_table_type>,"itab w/ no header line

     DATA:<wa_table>type <line_type>.  " work area for t_table

   *   This example defines an itab using the table type we just defined above
   *  (Note: depending on which of the two above table types you choose,
   * this will define either a standard or sorted internal table.)

    DATA: t_vendor type ty_t_vendor,   " itab has no header line
          wa_vendor type ty_vendor_data." work area for t_vendor

  * declaration of an internal table using a table line type

    DATA: <t_table> type 
           [sorted|hashed|standard|index|any] table
            of <line_type> 
            with [unique|non-unique] key <key definition>]
            [with header_line].

  *  This example declares a standard, unsorted internal table

    DATA: t_vendor type ty_vendor_data occurs 0 with header line.

  *  This example declares an internal table sorted by vendor number

    DATA: t_vendor type sorted table of ty_vendor_data
                 with unique key lifnr.
            with header line.

ABAP/4 Tuning Checklist


The general performance standards above outline ways to increase efficiency from many different perspectives, the following checklist was developed by SAP to quickly review the most common performance problems.   Please note that some of the information may overlap with the general performance section.
Checkbox.gif (229 bytes)Is the program using SELECT * statements?
Blue Arrow.gif (140 bytes)    Convert them to SELECT column1 column2 or use projection views.
Checkbox.gif (229 bytes)Are CHECK statements for table fields embedded in a SELECT ... ENDSELECT loop?
Blue Arrow.gif (140 bytes)    Incorporate the CHECK statements into the WHERE clause of the SELECT statement.
Checkbox.gif (229 bytes)Do SELECTS on non-key fields use an appropriate DB index or is the table buffered?
Blue Arrow.gif (140 bytes)    Create an index for the table in the data dictionary or buffer tables if they are read only or read mostly. Please consult R3-Admin for creation of indexes on or the buffering of SAP supplied tables.
Checkbox.gif (229 bytes)Is the program using nested SELECTs to retrieve data?
Blue Arrow.gif (140 bytes)    Convert nested SELECTs to database views, DB joins (v4.0), or SELECT xxx FOR ALL ENTRIES IN ITAB. Click here for a discussion on "for all entries".
Checkbox.gif (229 bytes)Are there SELECTs without WHERE condition against tables that grow constantly (BSEG, MKPF, VBAK)?
Blue Arrow.gif (140 bytes)    Program design is wrong - back to the drawing board.
Checkbox.gif (229 bytes)Are SELECT accesses to master data tables buffered (no duplicate accesses with the same key)?
Blue Arrow.gif (140 bytes)    Buffer accesses to master data tables by storing the data in an internal table and filling the table with the READ TABLE ... BINARY SEARCH method
Checkbox.gif (229 bytes)Is the program using SELECT ... APPEND ITAB ... ENDSELECT techniques to fill internal tables?
Blue Arrow.gif (140 bytes)    Change the processing to read the data immediately into an internal table (SELECT VBELN AUART ... INTO TABLE T_VBAK ...)
Checkbox.gif (229 bytes)Is the program using SELECT ORDER BY statements?
Blue Arrow.gif (140 bytes)    Data should be read into an internal table first and then sorted unless there is an appropriate index on the ORDER BY fields
Checkbox.gif (229 bytes)Is the programming doing calculations or summarizations that can be done on the database via SUM, AVG, MIN, or MAX functions of the SELECT statement?
Blue Arrow.gif (140 bytes)    Use the calculation capabilities of the database via SELECT SUM, ...
Checkbox.gif (229 bytes)Are internal tables processed using the READ TABLE itab WITH KEY ... BINARY SEARCH technique?
Blue Arrow.gif (140 bytes)    Change table accesses to use BINARY SEARCH method
Checkbox.gif (229 bytes)Is the program inserting, updating, or deleting data in dialog mode (not via an update function module)?
Blue Arrow.gif (140 bytes)    Make sure that the program issues COMMIT WORK statements when one or more logical units of work (LUWs) have been processed.


ABAP Reports

 

VIII. NAMING STANDARDS

In general, any custom developed programs or objects should be named with the "Z" for the first character. SAP has designated objects beginning with the letters "Y" and "Z" as customer named objects and ensures that this name space will not be overwritten during an upgrade. At MIT, we have started using the convention that objects whose names begin with "Y" are intended for "one time use" and objects whose names begin with "Z" are intended "regular" use.   An example of a program that should start with 'Y' would be a program that was written for the Y2K conversions.   Also, programs that are not intended to be migrated to Production should begin with "Y".

Also, SAP regularly updates the recommended customer name ranges for all development objects. For objects not included in this guide, please consult this SAP-created document. It is located on the SAP OSS system in note #16466.

In R/3 release 3.0F, ABAP report names were limited to 8 characters. In R/3 release 4.6C, ABAP report names can now be up to 40 characters long.

Position
 Usage
1
'Y' if program will not be migrated to production
'Z' if program will be migrated to production
 2-3
Application Name Abbreviation (see table following)
 4-40
Any (up to) 37-character acronym or words describing the program

Examples:

However, if the ABAP program is being created as a global data include or subroutine include, it should be formatted as follows:
 
Position
  Usage
  1
'Z' as required for customer development
 2-37
same as positions 4-39 in the main program
last 3 characters
'TOP' if used for global data, data declarations, table declarations
'F##' for subroutines where ## is a number, 00 through 99.

Examples:

Classification Objects and Class Types

Since classification objects and class types are more like programming data constructs than they are like configuration data, MIT naming conventions should be followed when creating new classification objects or class types.   To differentiate between SAP supplied classes and MIT developed classes the prefix 'MIT_' should be used followed by either the SAP data element or a descriptive abbreviation.  For example, when creating a characteristic for a 'Profit Center' where the data element is 'PRCTR' the name would be 'MIT_PRCTR'.  In addition, SAP recommends using only letters from A-Z, digits 0-9, and the underscore character in the name.

Development Classes

Development classes should only be created when a specific new project requires all components to be linked for organizational purposes. Before creating a new development class, please consult with the Technical Services Team <tech-services@mit.edu >. See Appendix C for a list of development classes.

Directories for file I/O

Most SAP system interfaces using flat ASCII files for input or output should use the following directory paths for temporary and permanent interface files.

The variable [environment name] should be determined at run-time by the program. To generate this name, use the function Z_DETERMINE_FUNC_AREA. This function will identify the [environment name] section of the path based on the system id and the client of the calling R/3 system.

Sample code follows:
data: begin of myfile, 
        part1(13) value '/usr/bridges/', 
        part2(15), "dev2 or tst1 or prod 
        part3(9) value '/saptmp/', 
        part4(30) value 'flname', 

      end of myfile. 

initialization.

  call function 'Z_DETERMINE_FUNC_AREA' 

    importing 

      func = myfile-part2 

    exceptions 

      unknown_sysid = 1 
      unknown_mandt = 2. 

  if sy-subrc eq 0. 

    condense myfile no-gaps. 

  endif.

Function Groups are named using the following convention:

Position
 Usage
 1
'Z' as required for customer development
 2-3
Application Name Abbreviation (see Appendix B)
 4
Sequential group number

Function Groups

For example, ZBR0 is the function group for application "BR" for "Bridges" and number "0" sequentially. Before creating a new function group, please consult with Technical Services.

Function Modules

Function module names should be as descriptive as possible given that there are 30 characters available for naming. They should be formatted as follows:

Position
  Usage
  1
'Z' as required for customer development
 2
'_' (an underscore)
 3-4
Application Name Abbreviation (see Appendix B)
 5-30
any use of descriptive words separated by underscores

Check Modules for External Commands

In the special case of function modules which are used as check modules for external commands, their names follow different rules. Such function modules should be created in the function group "SAPLZEXT_CMD_CHECK_MODULES" and given names of the form "Z_CK_EXTCMD_<external-command>" (where <external-command> represents the actual name of the External Command whose invocation is checked by this function module before the External Command is executed).

Module Pools

Module pools should be named as follows:


Position
  Usage
  1-3
'SAPM' as required by the system to denote online modules
 5
'Z' to denote customer named object
 6-7
Application Name Abbreviation (see Appendix B)
 8
Sequential Number (0-9)

Module pool includes should be named as follows:

Position
  Usage
  1
'M' as required by the system to denote online modules
 2
'Z' to denote customer named object
 3-4
Application Name Abbreviation (see Appendix B)
 5
Sequential Number (0-9) corresponding to main program
 6
'I' for PAI modules, 'O' for PBO modules, 'F' for subroutines
 7-8
Sequential Number (00-99)
 6-8
'TOP' if the include is the global data include

Naming Conventions in ABAP Objects

Introduction

ABAP Objects' namespace validity is very complex. In order to avoid problems during
development it is not only helpful but also necessary to outline name conventions
for that matter.

Classes and their dependent subclasses share the same namespace which affects

        Constants (CONSTANTS) ,
   Variables (DATA, CLASS-DATA) ,
   Methods (METHODS, CLASS-METHODS) and
   Events (EVENTS, CLASS-EVENTS).

SAP has not yet decided whether to allow upper/lower case for internal names (to separate individual words - as in JAVA). Therefore in order to do that we still have to use the underscore character.

Naming Conventions

General rules:

General Conventions:

   Class in Class Library*    ZCL_<class name>

   The class name should consist of nouns and should only use the 
   singular form: 
   ZCL_COMPANY_CODE 
   ZCL_GENERAL_LEDGER_ACCOUNT

   Interfaces in ClassLibrary*    ZIF_<interface name>

   The naming conventions for classes also apply to interface:. 
   ZIF_STATUS_MANAGEMENT, 
   ZIF_CHECKER

   Types in the DDIC*    Z<type name>

   Local Class
   LCL_<class name>

   The class name should consist of nouns and should only use the 
   singular form: 
   LCL_TRANSACTION

   Local Interface   LIF_<interface name>

   The class name should consist of nouns and should only use the 
   singular form: 
   LIF_PRINTER 

Objects marked with * are protected by the global TADIR, but they occupy the same namespace as data elements, tables, structures and types.

Class Conventions
Method Name   <method name>

  The method name should begin with a verb. 
  GET_STATUS, CREATE_ORDER, 
  DETERMINE_PRICE

Event   <event name>

  Event names should be named like this: 
  <Noun>_<Participle of Verb >. 
  BUTTON_PUSHED, 
  COMPANY_CODE_CHANGED, 
  BUSINESS_PARTNER_PRINTED

 Local Class Type Definition   <type name>_ty

  INTERNAL_TYPE_TY, 
  TREE_LIST_TY

 Data Definition (Variable)   <variable name>

  You should avoid using verbs at the beginning when naming 
  variables within a class (CLASS-DATA, DATA). 
  (This is to prevent confusion with method names.) 
  LINE_COUNT, MARK_PRINTED, 
  MARK_CHANGED, STATUS

 Data Definition (Constants)   C_<constant name>

  C_MAX_LINE, 
  C_DEFAULT_STATUS, 
  C_DEFAULT_WIDTH, 
  C_MAX_ROWS 

Fixed Method Names
 Attribute Accesses   SET_<attribute name>,
  GET_<attribute name>

  You should prefix all types of attribute access with GET_ 
  or SET Accordingly, 
  GET_STATUS, 
  SET_USE_COUNT

Methods that Deal with an Event   ON_<event name>

  For methods that deal with an event, you should begin the 
  name with ON followed by the name of the relevant event. 
  ON_BUTTON_PUSHED, 
  ON_BUSINESS_PARTNER_PRINTED

Methods that carry out Type Conversions   AS_<new Type>

  AS_STRING, 
  AS_ISOCODE

Methods that deliver a Boolean Value

  These methods cannot return 
  any EXCEPTIONS. 
  Recommendation: The 
  Boolean value should be 
  represented by SPACE/"X" for 
  False/True. 
 

  IS_<adjective>

  IS_OPEN, IS_EMPTY, 
  IS_ACTIVE

 Check Methods

  These methods differ from the 
  IS_<adjective>" methods by 
  their ability to return 
  exceptions. 
  CHECK_AUTHORIZATION, 
  CHECK_PROCESS_DATE 
 

  CHECK_<objective>

  CHECK_AUTHORIZATION, 
  CHECK_PROCESS_DATE 

Method Conventions

The parameters are observed from the point of view of the methods, which implemented them:
IMPORTING-Parameter  IM_<parameter name>
EXPORTING-Parameter  EX_<parameter name>
CHANGING-Parameter  CH_<parameter name>
RESULT  RE_<result>
EXCEPTIONS  See "Exceptions"

Exceptions
The developer"s job is made easier when standards for the naming of exceptions are available. The following is a table of meaningful exceptions, which can also be used generically.
(Example: ...NOT_FOUND could become DATE_NOT_FOUND)
 EXCEPTION            MEANING
ACTION NOT SUPPORTED The requested action or the requested OK-Code is not supported
CANCELLED This EXCEPTION can be set if the user is required to select what happens next in a method (for example: Selection List) and he/she selects "Cancel".
EXISTING A new object already exists in the database.
FAILED The methods could not carry out your task because of the present state of the environment. This exception is especially intended for cases where the environment is temporarily in a situation that does not allow the method tasks to be carried out.
..._FAILED A sub function of the method could not be carried out because of the present state of the environment. (OPEN_FAILED, CLOSE_FAILED, SELECTION_FAILED, AUTHORIZATION_FAILED)
FOREIGN_LOCK Other users lock data.
INCONSISTENT Object data in the database is inconsistent.
..._INCONSISTENT The sub-object data of an object in the database is inconsistent.
INVALID The object data entered is not correct. (e.g. Company Code is not available) (in contrast to NOT_QUALIFIED)
..._INVALID The given sub-object data of an object is not correct. (In contrast to NOT_QUALIFIED)
INTERNAL_ERROR The last resort. If all else fails and the error can no longer be contained, apply this EXCEPTION.
NOT_AUTHORIZED The user does not have authorization for this action.
NOT_CUSTOMIZED The object requested is not correctly customized.
..._NOT_CUSTOMIZED The sub-object of the object requested is not correctly customized.
NOT_FOUND The requested object has not been found.
..._NOT_FOUND  The sub-object of the object requested has not been found.
NOT_QUALIFIED The combination of input parameters is not sufficient to allow the method"s functions to be carried out. (In contrast to INVALID)
..._NOT_QUALIFIED A specific parameter of the method is not qualified
NUMBER_ERROR Error in the provision of numbers.
SYSTEM_ERROR This exception can be set where the Basis System registers an unexpected error code.

Please note:
SAP Basis Technology is presently implementing class-based exception handling like we have in JAVA. The error classes – from the development point of view a welcome simplification of error handling, which is clearly preferred – should then replace EXCEPTION-handling as we use it now. This will however not be available for 4.6c. A standardized usage of the EXCEPTIONS named above will simplify the move to this error class and allow a part-automated move.

ABAP: Passing unknown table structures into functions


This new class-based exception handling is scheduled to be implemented and delivered with Basis Rel. 6.10 as part of R/3 Core release 4.7 (R/3 Enterprise). Availability not before Q2 2002.


VIII. TIPS & TRICKS

Typically function modules must specify the exact structure of each parameter they are passed, hence runtime structures cannot be handled easily in normal function module creation. However, by using the ABAP programming construct ASSIGN COMPONENT idx OF STRUCTURE record to <FS>, a function can determine the structure of a record. For an example of how to develop a function to do this refer to function Z_LIST_SELECT_OPTIONS which reads the structure of a RANGES table in a SELECT-OPTION parameter.

ABAP: Multi-dimensional arrays

Support for one and two-dimensional arrays within ABAP is provided through the use of internal tables.  However, in the case of a 3-dimensional array, ABAP has no native programming constructs.  While a method could be devised to index a 3-dimensional array via internal tables, the following code fragment demonstrates an alternative approach using field symbols as pointers into data structures:
* This code fragment illustrates the use of a field symbol
* and an ASSIGN statement to get the effect of having
* multi-dimensional subscripted arrays. There are several
* costs of this method. One is performance and the other
* is that EVERY cell in the multi-dimensional array
* must be declared in a DATA (or CONSTANT, etc.) statement
* at the beginning of the program.

* Using this method, you would have to have DATA statements
* like the following four for EACH CELL of the 
* multi-dimensional array.
 

DATA: VARA_001_005_006(11) VALUE 'Some value!'.

DATA: VARA_002_005_006(11) VALUE 'Other value'.

DATA: VARA_003_005_006(11) VALUE 'Next value!'.

DATA: VARA_004_005_006(11) VALUE 'The target!'.
 

DATA: BEGIN OF POINTER,

        STEM(5) TYPE C VALUE 'vara_',

        PART1(3) TYPE N,

        SEP1(1) TYPE C VALUE '_',

        PART2(3) TYPE N,

        SEP2(1) TYPE C VALUE '_',

        PART3(3) TYPE N,

      END OF POINTER.
 

DATA POINTER_DEFAULT(11) VALUE 'The default'.
 

FIELD-SYMBOLS: <INDIRECT>.
 

* This is the example of using the multi-dimensional array in
* the body of a program. You would have to have use something
* like the following PERFORM for each change to the
* subscripts in a reference to the multi-subscripted variable.

PERFORM ASSIGN_POINTER_3 USING 'vara_' 4 5 6.

WRITE: / 'Indirectly referencing through pointer,
          we get:', <INDIRECT>.
 

PERFORM ASSIGN_POINTER_3 USING 'vara_' 10 11 12.

WRITE: / 'Indirectly referencing through pointer,
          we get:', <INDIRECT>
 

PERFORM ASSIGN_POINTER_3 USING 'vara_' 1 5 6.

WRITE: / 'Indirectly referencing through pointer,
          we get:', <INDIRECT>.

FORM ASSIGN_POINTER_3 USING STEM SUB1 SUB2 SUB3 .

  POINTER-STEM = STEM.

  POINTER-PART1 = SUB1.

  POINTER-PART2 = SUB2.

  POINTER-PART3 = SUB3.
 

  ASSIGN (POINTER) TO <INDIRECT>.

  IF SY-SUBRC <> 0.

    ASSIGN POINTER_DEFAULT TO <INDIRECT>.

  ENDIF.

ENDFORM. " ASSIGN_POINTER_3

ABAP: Type coercion

Type coercion is typically defined as the means to force a variable of one type to be another type.  In ABAP programming, type coercion is most useful for the ASCII conversion of character data.  The following code fragment is an example of coercion which outputs ASCII character data:
data: begin of hex,
        byte type x,
      end of hex.

data: char type c.

data: temp like sy-index.

do 224 times.

 temp = sy-index + 31.
 

 hex-byte = temp.
 

 char = hex.
 

 write: / 'Decimal =', temp.
 write:   'Hex     =', hex-byte.
 write:   'View    =', char.

enddo.

BDC: Formatting date fields to be compatible with user preferences

When writing BDCs that read dates to be entered into SAP transactions (either by generating batch input sessions or by using call transaction) problems occur when determining what date format to use when entering the data into its corresponding field. Assume that the ABAP program that must call the transaction (or generates the batch input session) can read the 'date' field properly from the input file, but it does not know which format the data entry screen of the transaction requires as this may change based on the user"s setup defaults.

The current best approach to solving this problem is:

  1. Declare a date variable in the interface program to be LIKE SY-DATUM.
  2. Then, store the date (read from the input file) in the date variable in the correct internal form (YYYYMMDD).
  3. Write that date variable to a character string variable.
  4. Use the character string variable as the value of the date field in the transaction screen

BDC: Formatting a number to be compatible with user preferences 

When writing BDCs that read numbers to be entered into SAP transactions (either by generating batch input sessions or by using call transaction) problems occur when determining what number format to use when entering the data into its corresponding field. Assume that the ABAP program that must call the transaction (or generates the batch input session) can read the 'number' field properly from the input file, but it does not know which format the data entry screen of the transaction requires as this may change based on the user"s setup defaults.

The current best approach to solving this problem is explained by the following example code:
* Assume we have a numeric value in the variable "Amount" and we
* want to format it into the variable "String" for entry into a
* transaction field.

data amount like bseg-wrbtr.

data string(20).

data temp(2).

write amount to string currency 'USD'.
 

* String+19(1) is a possible minus sign
* String+17(2) is the number of cents
* String+16(1) is the decimal point
* String+13(3) is the three digits to the left of decimal
* String+12(1) is a possible thousands separator

temp = string+12(1). " String is 20 chars. 20 - 8 = 12

* If there are any thousands separators, change them to spaces.

if temp(1) cn '0123456789'.

  translate string using temp.

endif.

* Remove any spaces

condense string no-gaps.

Conversions: Legacy-to-SAP cost objects and G/L accounts

Prior to our 4.5B upgrade, we had programs and interfaces which converted MIT legacy cost objects and accounts to the corresponding SAP account or object. Two custom MIT function modules were developed for use in this conversion process. We are no longer converting from the legacy system to SAP. The function modules have been modified so that they will raise an exception if asked to convert from the legacy architecture. As code is modified, calls to these function modules should be removed. The names of these function modules are Z_GET_COST_OBJECT and Z_GET_GL_ACCOUNT.

UNIX : Calling UNIX commands and scripts from ABAP Programs

Often it is necessary to execute an external program as part of an ABAP program, however, you should be very careful in doing so because any external command is executed as the UNIX user <SID>adm. For example, if a program is written to call the command "rm" on the development system it is executed at the system level as the user "sf2adm".

For an example of how to call UNIX system commands, look at program ZUNIXCMD on system SF2. Remember, you can call external programs either synchronously so that your ABAP program will wait until they complete before continuing, or you can call them asynchronously so that your ABAP program will continue execution immediately.

Earlier programs written at MIT used the "CALL SYSTEM" command. In the future, this command should not be included in any new programs and should be removed from existing programs when they are revised.


Appendix A: Sample Programs

REPORT ZSKELREP.
*----------------------------------------------------------------
* Purpose:
*
*
*
*----------------------------------------------------------------
* Author:
* Date:
*----------------------------------------------------------------
* Revision History:
*
*----------------------------------------------------------------
TABLES: ...
 

DATA: ...

SELECT-OPTIONS: ...

PARAMETERS: ...

FIELD-GROUPS: HEADER, ...

FIELD-SYMBOLS: ...
 

* Event which occurs before the selection screen is shown to
* the user. 

INITIALIZATION.

* Event which occurs each time the user hits enter on the
* selection screen. This event is ignored in background
* processing.
 

AT SELECTION-SCREEN.

TOP-OF-PAGE.

END-OF-PAGE.

START-OF-SELECTION.

* Definition of fields for FIELD-GROUP extract

INSERT: ... INTO HEADER.

GET ...

END-OF-SELECTION.

SORT ...
 

LOOP ...

  AT FIRST.

  ENDAT.
 
 

  AT NEW ...

  ENDAT.
 

  AT END OF ...

  ENDAT.
 
 

  AT LAST.

  ENDAT.

ENDLOOP.

* Subroutines
*----------------------------------------------------------------
*
*
*----------------------------------------------------------------
FORM ...

ENDFORM.

Basic ABAP/4 List Report


Interactive ABAP/4 List Report

REPORT ZSKELINT.
*----------------------------------------------------------------
* Purpose:
*
*
*----------------------------------------------------------------
* Author:
* Date:
*----------------------------------------------------------------
* Revision History:
*
*----------------------------------------------------------------

TABLES: ...

DATA: ...

SELECT-OPTIONS: ...

PARAMETERS: ...

FIELD-SYMBOLS: ...
 

FIELD-GROUPS: ...

* Event which occurs before the selection screen is shown to
* the user. 

INITIALIZATION.

* Event which occurs each time the user presses any button on
* the selection screen. This event is ignored in
* background processing.

AT SELECTION-SCREEN.

TOP-OF-PAGE.

* Top of page for sublists

TOP-OF-PAGE DURING LINE-SELECTION.

END-OF-PAGE.

START-OF-SELECTION.

GET ...

END-OF-SELECTION.

* Produce main list report SY-LSIND = 0.

SORT ...

LOOP...

 WRITE:/ ...

* Hide specific fields which are of importance to the line

  HIDE: ...

ENDLOOP.

* Event which occurs when user hits a particular F key, i.e. F6
* The hide area and SY-LISEL are automatically available.
* Produces a sublist SY-LSIND = 1-9. F3 is automatic, will always
* take the user back one list level, (SY-LSIND - 1).

AT PF...

* Event which occurs when a user types =LIST in the OK code
* The hide area and SY-LISEL are automatically available.
* Produces a sublist SY-LSIND = 1-9. F3 is automatic, will always
* take the user back one list level, (SY-LSIND - 1).

AT USER-COMMAND.

 CASE SY-UCOMM.

  WHEN 'LIST'. .....

 ENDCASE.

* Event which occurs when the user places the cursor on a specific
* line on the report and hits F2, double-clicks a line, or clicks
* on a hot spot.
* The hide area and SY-LISEL are automatically available.
* Produces a sublist SY-LSIND = 1-9. PF3 is automatic, will always
* take the user back one list level, (SY-LSIND - 1).

AT LINE-SELECTION.

* Subroutines
*----------------------------------------------------------------
*
*
*----------------------------------------------------------------

FORM ...
 

ENDFORM.


Create a Sequential Dataset

REPORT ZSKELOUT.
*----------------------------------------------------------------
* Purpose:
*
*
*
*----------------------------------------------------------------
* Author:
* Date:
*----------------------------------------------------------------
* Revision History:
*
*----------------------------------------------------------------
TABLES: ...

DATA: ...

SELECT-OPTIONS: ...
PARAMETERS: ...

FIELD-SYMBOLS: ...
 

START-OF-SELECTION.

GET ...

MOVE ... TO ...

WRITE ... TO ...

UNPACK ... TO ...

TRANSFER ... TO ...

END-OF-SELECTION.

* Subroutines
*----------------------------------------------------------------
*
*
*----------------------------------------------------------------
FORM ...

ENDFORM.


Read Sequential Dataset and Create a BDC Session

report zskelbdc.
*-----------------------------------------------------------------
* Purpose:
*
*
*-----------------------------------------------------------------
* Author:
* Date:
*-----------------------------------------------------------------
* Revision History:
*
*-----------------------------------------------------------------
tables: ...

data: t_bdcdata like bdcdata occurs 0 with header line.

data: t_messtab like bdcmsgcoll occurs 0 with header line.

data: begin of t_tab occurs ...

      end of t_tab.

select-options: ...

parameters: ...

field-symbols: ...

*----------------------------------------------------------------*
start-of-selection.

  open dataset p_dataset in text mode. 

  if sy-subrc <> 0.

    write: / text-e00, sy-subrc. 

    stop. 

  endif. 

*--- Open the BDC Session ---------------------------------------*

write: /(20) 'Create group'(i01), group.

skip. 

call function 'BDC_OPEN_GROUP' 

     exporting client   = sy-mandt 
               group    = group 
               user     = user 
               keep     = keep 
               holddate = holddate. 

write: /(30) 'BDC_OPEN_GROUP'(i02), (12) 'returncode:'(i05), 

      sy-subrc. 

*----------- DYNPRO nnn -----------------------------------------*

perform bdc_dynpro using 'SAPMxxxx' 'nnn'.

perform bdc_field using 'TABL-FIELD' 'LITERAL'.

*----------- DYNPRO nnn -----------------------------------------*

perform bdc_dynpro using 'SAPMxxxx' 'nnn'.

perform bdc_field using 'TABL-FIELD' TAB-VAR.

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

call function 'BDC_INSERT' 

     exporting tcode  = tcode 

     tables dynprotab = t_bdcdata. 

write: /(25) 'BDC_INSERT'(i03), tcode, 

        (12) 'returncode:'(i05), sy-subrc.

close dataset p_dataset.

*----- Close the BDC Session -----------------------------------

call function 'BDC_CLOSE_GROUP'. 

write: /(30) 'BDC_CLOSE_GROUP'(i04), 

        (12) 'returncode:'(i05), sy-subrc. 

end-of-selection.

*----------------------------------------------------------------
* Subroutines *
*----------------------------------------------------------------
*--- Add a line to the DYNPRO Table ----------------------------

form bdc_dynpro using program dynpro.

  clear t_bdcdata.

  t_bdcdata-program = program. 

  t_bdcdata-dynpro = dynpro. 

  t_bdcdata-dynbegin = 'X'. 

  append t_bdcdata. 

endform. 

*--- Add a field to a DYNPRO ------------------------------------

form bdc_field using fnam fval. 

  clear t_bdcdata.

  t_bdcdata-fnam = fnam. 

  t_bdcdata-fval = fval. 

  append t_bdcdata. 

endform.

CALL TRANSACTION USING Technique

REPORT ZSKELCLT.
*----------------------------------------------------------------
* Purpose:
*
*
*-----------------------------------------------------------------
* Author:
* Date:
*-----------------------------------------------------------------
* Revision History:
*
*-----------------------------------------------------------------
tables: indx, ...

data: return_code like sy-subrc,

      message_text(120).

data: begin of t_trantab occurs 10.

        include structure bdcdata.

data: end of trantab.
 

select-options: ...

parameters: ...

field-symbols: ...
 

start-of-selection.

*----------- DYNPRO nnn -----------------------------------------*

perform bdc_dynpro using 'SAPMxxxx' 'nnn'.

perform bdc_field using 'TABL-FIELD' 'LITERAL'.

*----------- DYNPRO nnn -----------------------------------------*

perform bdc_dynpro using 'SAPMxxxx' 'nnn'.

perform bdc_field using 'TABL-FIELD' TAB-VAR.

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

call transaction ' ' using t_trantab mode 'N' update 'S'.
 

* Message handling

return_code = sy-subrc.

data: message_text(80) type c. 

MESSAGE ID SY-MSGID 
TYPE 'S' NUMBER SY-MSGNO 
WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4 INTO MESSAGE_TEXT.

if return_code = 0.

* At this point, various things can be done to make the
* process slicker.
* Send the confirmation or error to the other program via RFC.
* Store key values and confirmation document number or error
* message in an internal table for future processing.

  move 'Transaction posted' TO ...

  move message_text to ...

  modify ...

else.

  move 'Transaction failed' to ...

  move message_text to ...

  modify ...

* In the event of errored transactions:
* Store the internal table in the INDX database for future online
* processing of the SAP transaction.

  export t_trantab to indx(..) id ...

endif.

* Or create a batch input session for future processing.

refresh t_trantab.

end-of-selection.

*----------------------------------------------------------------
* Subroutines *
*----------------------------------------------------------------
*--- Add a line to the DYNPRO Table ----------------------------

form bdc_dynpro using program dynpro.

  clear t_bdcdata. 

  t_bdcdata-program = program. 

  t_bdcdata-dynpro = dynpro. 

  t_bdcdata-dynbegin = 'X'. 

  append t_bdcdata. 

endform. 

*--- Add a field to a DYNPRO ------------------------------------

form bdc_field using fnam fval. 

  clear t_bdcdata. 

  t_bdcdata-fnam = fnam. 

  t_bdcdata-fval = fval. 

  append t_bdcdata. 

endform.


Appendix B: Two-character codes for application areas

The following two-character abbreviations are used to identify certain projects or modules when naming programming objects. . (Note that SAP has associated many two-character codes with specific application areas, even though they do not appear in this list.)

Please do not use any code not listed here, and do not use a code for any application area other than the one associated with the code in this list.

If you have an application area which is not listed here, please discuss the situation with Technical Services Team Leader. He will talk with you and either determine that your project should be classified as belonging to an application already listed here, or (after checking SAP-assigned codes) he will assign a new code for the new application area.

2-Character Abbr.
  Application Name
Devel. Class- MIT Devel. Class-
Lincoln
AA
Asset Accounting    ZKG0 .
AC
Accounting General . .
AP
Advanced Planner and Optimizer    ZAP0 .
AR
Accounts Receivable    ZAR0 .
AU
Authorization Checks    ZSB0/    ZR30 .
BC
Basis Components  . .
 BD
Broad Institute    ZBD0  
 BP
Buy-Pay Process (incl. Purchasing)    ZSC0/    ZUT0/    ZSB0 .
 BR
Bridges / Infrastructure    ZBR0 .
 BU
Budget (SAPBud)    ZBUD0 .
 BW
Business Information Warehouse . .
    CA** CS Cashier's Office    ZCS0 .
CA
Cross-Application Components . .
 CD
Change Documents . .
 CK
Ckeck Modules (see the section on "Check Modules for External Commands")    ZUT0 .
 CO
Controlling    ZKG0 .
     CS **
CU
Customer Service . .
EC
Enterprise Controlling (or Electronic Commerce) . .
EH
Environment, Health & Safety  ZEH0 .
EP
Internet Portal ZEP0  
ER
Extended Relationship Management . .
ES
Enterprise Structure    ZES0 .
FC
(MIT) Credit Card    ZCC0 .
FF
Funds Center    ZFF0 .
FI
Financial Accounting    ZGL0 .
 GL
General Ledger    ZBR0 .
HR
Human Resources    ZHR0 .
IM
Investment Management . .
IS
Industry-Specific Components . .
KM
SAP Knowledge Management . .
 L*
Labor Distribution System   ZLD0 .
LE
Logistics Execution . .
LO
Logistics - General . .
MM
Materials Management . .
MP
mySAP.com Marketplace . .
MS
Mobile Sales . .
PA
Personnel Management . .
PE
Training and Event Management    ZPE0 .
 PM
Plant Maintenance    ZPM0 ZLCP1_PM0
PP
Production Planning and Control  (or Physical Plant)    ZPP0 .
PS
Project System    ZSB0 .
PT
Personnel Time Management . .
PY
Payroll Accounting    ZPY0 .
QM
Quality Management . .
R3
MIT Basis    ZR30 .
RE
Real Estate Management   ZRE0 .
RQ
Requisitions . .
SD
Sales and Distribution    ZSB0 .
SE
Strategic Enterprise Management . .
SV
Service . .
    TR **
TY
Treasury . .
TR
Travel    ZTR0 .
TS
Time Sheet (CATS Related) . .
UT
Utilities and Tools    ZUT0 .
 WF
Workflow    ZWF0 .
 WH
(MIT) Data Warehouse    ZWH0 .
WP
mySAP.com Workplace . .
XX
Miscellaneous . .
IMG Documentation . ZLCP1_IMG

**   should NOT be used for new programs created after October 1, 2001.


Appendix C: Development Classes

SAP Repository objects are classified according to development classes. It is recommended that functionally related objects (such as programs, dictionary components, message classes, etc...) be grouped together by development class. For example, code development for Accounts Payable would be in development class ZAP0. This structuring of the SAP object repository facilitates the control and recording of development efforts.

Please consult with Technical Services Team < tech-services@mit.edu > regarding the creation of new development classes or the uses of existing classes.
DEVEL.
CLASS
DESCRIPTION
Z001  Customer Development Class
ZAP0 Accounts Payable
ZAR0 Accounts Receivable
ZBC404 ABAP Object Class
ZBD0 Broad Institute
ZBF0 Business Framework Architecture: Customer Development
ZBFA Business Framework Architecture
ZBP0 Buy/Pay
ZBR0 Bridges and Feeds
ZBR1 ABAP Bridges and Feeds
ZBUD0 Budget project (SAPBud)
ZCC0 Credit Card Processing
ZCS0 Cashier Office
ZCT0 Computer Aided Test Tools
ZED0 EDI
ZEH0 Environment, Health & Safety
ZEP0 Internet Portal
ZES0 Multiple Enterprise Structure
ZEI0 EIS
ZFF0 Fund Center: custom development
ZFX0 Field Exits: Customer Development
ZGL0 General Ledger
ZGN0 General/Miscellaneous
ZHR0 H/R Application: Customer Development
ZIF0 ITS Financial
ZKA0 Availability checking in CO
ZKG0 Controlling
ZLD0 Labor Distribution System
ZPE0 Training and Events Management
ZPM0 Plant Maintenance
ZPP0 Physical Plant
ZPY0 Payroll Accounting (Employee and Pension)
ZR30 R/3 Administration
ZR31 R/3 Administration: SAP Tools/Development
ZRE0 Real Estate Management: Customer Development
ZRF0 Remote Function
ZRV0 Technology Review Development
ZSB0 Sponsored Billing
ZSC0 SAPScript/Word Processing
ZSL0 Sloan School Support
ZSP0 SPO Legacy Link Program Product
ZTR0 Travel
ZUS0 SPO Bridge Development Program Product
ZUT0 Tools & Utilities
ZUT1 Tools & Utilities for EDI
ZWB0 SAP Workbench Training: Instructor
ZWB1 SAP Workbench Training: Workshop
ZWF0 SAP Business Workflow
ZWH0 Data Warehouse
ZZZ0 Obsolete Programs

Notes:


Appendix D: Approval process for Direct Update to SAP table & SAP source code modification

Very rarely, a business scenario arises for which the most viable solution is to write code that directly updates SAP table data ("Direct Update") or to make a modification to SAP source code ("Mod"). Our rule is to avoid doing either. Below is process for a developer to follow if he/she facing a situtation where a Direct Update or Mod is needed:

  1. Prepare the business justification as to why a Direct Update to an SAP table or Mod to SAP code is needed.
  2. Identify the risks of doing the Direct Update or Mod.
  3. Identify alternatives.
  4. Analyze the impact & cost of not doing the Direct Update or Mod.
  5. Make the presentation to the Technical Services Team Leader.
  6. Depending upon the scope of the Direct Update or Mod, further approval might be required by AD-Leadership Team, Director or VP of IS&T.