Coding Standards
Coding Standards
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.
MOVE ...
APPEND ...
ENDSELECT.
END-OF-SELECTION.
LOOP AT tab.
AT NEW f1.
CASE F1.
WHEN ...
WRITE: ...
WHEN ...
WRITE:/ ...
ENDCASE.
ENDAT.
Making Programs and Function Modules 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 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 [email protected] . Please be sure to send
your e-mail before releasing the program from SF2.
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
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:
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:
4f. "Deactivate" the function module so that the system will automatically comment out the
include file for the function module from the function group. (On the first screen of
transaction SE37, Right-Click (on a PC) or Command-Click (on a Mac) to bring up a menu
of commands. Select the "Deactivate" command.)
FUNCTION Z_INSERT_TR_ACCOUNT .
*********** This function module is OBSOLETE ***********
**"----------------------------------------------------------------
-----
*
**"*"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.
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.
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:
• Programs that can be executed by all MIT users must be configured using the
authorization group 'ZOPN2ALL' for Application '*'. This configuration is done by the
developer of the report program in the 'Attributes' screen of SE38 .
• Programs that should only be executed by a restricted set of users should have an
authorization group that is defined to include only that set of users. (In many cases, it
may be desirable for a large set of developers and testers to have that authorization in
SF2, a smaller set to have that authorization in SF5, and an even more restricted set to
have that authorization in production.)
• Some programs have other authorization controls (for example, the program may
provide particular functionality to certain users as determined by the ABAP
"AUTHORITY-CHECK" command or an authorization checking function module), but
other functionality is available to everyone. In that case the program should use the
'ZOPN2ALL ' authorization group in addition to its explicit use of the ABAP
"AUTHORITY-CHECK " command or an authority checking function module.
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).
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.
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:
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.
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:
• Dates: As indicated in the section "Writing dates in reports," dates should use a 4-digit
year with certain exceptions.
• Cost Objects: Cost objects should be left-aligned in a 12-character field with trailing
blanks. (Optionally, a 7-character field followed by 5 characters of blank filler is
acceptable.
• Cost Elements: Cost elements should be left-aligned in a 10-character field with trailing
blanks. (Optionally, a 6-character field followed by 4 characters of blank filler is
acceptable.
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.
• Call Z_UT_GET_INPUT_FILE_NAME with the filename field from the selection-screen, the
(4-char) provider & the (3-char) feed codes and (optionally) the name of an acceptable
event.
• Call Z_UT_START_OF_INBOUND with the file name (from
Z_UT_GET_INPUT_FILE_NAME).
• Read & process the input file.
• Call Z_UT_END_OF_INBOUND when finished.
• Call Z_UT_START_OF_OUTBOUND with the (4-char) provider and the (3-char) feed code
to obtain the pathname of your output file.
• Do your processing, write the output file and accummulate control totals.
• Call Z_UT_END_OF_OUTBOUND with the key (in the ZJOBRUN2 table) for the output file
and the contents of the control record.
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).
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.
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.
• Z_CO_M
• ITID_TO_NAME - Convert MIT ID to name in format L /F M and as separate
components;
• Z_CO_COST_OBJECTS_FROM_MITID - Return a list of cost object numbers from MIT
id numbers passed in a range table;
• Z_CO_COST_OBJECT_NAMES - Return the names of the supervisor and addressee of
a given cost object;
• Z_CO_GET_MITID_POPUP - Display Popup of MITID information from a given select-
options.
In addition, collective search help ZMID is available for possible value help. It consists of two
elementary search helps:
• ZMIDA - Lists all MIT ID's in the system for given selection criteria;
• ZMIDB - Lists only those MIT ID's which are either supervisors or addressees of cost
objects.
Term
ZSTATUS Meaning
Code
None/Space X Valid cost object
1* X Valid cost object
2* X Valid cost object
Valid Terminated Cost Object (No
3 T
postings permitted)
4* X Valid cost object
Invalid cost object with no
8 8
charges/credits posted
Invalid cost object with charges/credits
9 9
posted
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.
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)
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.
4. Delivery class
Class SAP definition Comments
Applic. table (master and
A Should not be maintainable by SM30/SM31
transaction data)
Customizing table,
Used for Control type info, should be maintainable
C maintenance only by
by SM30/SM31
customer, not SAP import
Table for storing temporary
L Should not be used for MIT tables
data, delivered empty
Customizing table, This is for use on Customizing tables developed in
G protected against SAP cooperation with SAP. SAP can INSERT entries into
Update, only INS all this type of table, but cannot change or delete any.
Control table, SAP and
E customer have separate Should not be used for MIT tables
key areas
System table, maint. only
S by SAP, change = Should not be used for MIT tables
modification
System table, contents
W transportable via separate Should not be used for MIT tables
TR objects
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.
where:
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).
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
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
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
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.
• If there is very little data, have the foreground job use the SUBMIT command to pass
the actual data through selection screen parameters or select-options when creating
the background job.
• If there is more data, have the foreground job export it to the INDX table in the
database and us the SUBMIT command to pass the ID key through a selection screen
parameter when creating the background job.
• In some special cases, it might be better to create a new custom table and have the
foreground job load the data into the custom table, from which the background job will
retrieve it.
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:
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.
• For FI Tables, use the monetary amount in the company code currency firld, sometimes
described as the "local currency" field.
• For CO Table, use the monetary amount in the controlling area currency field.
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.
MONETARY FIELD
TABLE TABLE DESCRIPTION FIELD DESCRIPTION
TO USE *
BSEG Accounting Department Segment DMBTR Amount in local currency
COEP CO Object: Line Items(by period) WKGBTR Total value on CO area currency
CO Object: Cost Totals for External
COSP WKG99 Total value on CO area currency
Postings
CO Object: Cost Totals for Internal
COSS WKG99 Total value on CO area currency
Postings
G/L Account Master Transaction Total Transactions in the period
GLT0 HSL99
Figures in local currency
Project Info Database:
RSPCO WLP99 Period value in Ledger currency
Cost,Revenues,Finances
* The '9' 's in this column stand for a given period (1 through 16).
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-
[email protected] 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. "[email protected]". 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>[email protected] (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 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).
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 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.
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.
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).
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):
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):
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:
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:
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:
2. If the user CAN choose exactly one company code, include in the definition of the
selection screen either:
or:
3. If the user CAN choose one or more company codes, include in the definition of the
selection screen:
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
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.
INCLUDE ZES_AFTER_S_O_SEL_FOR_S_BUKRS.
1. Variables set when more than one company code is supplied (or implied):
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):
3. Additional variables set when only one company code is supplied (or implied):
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.
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.
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
1. If you want to know how many companies were selected, you can use the
following:
LOOP AT R_ES_BUKRS.
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.
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.
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.
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,
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
CL_GUI_FRONTEND_SERVICES class (rather than the WS_UPLOAD and
WS_DOWNLOAD function modules).
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.
In each radio button group exactly one button in the radio button group must be defaulted to
'X'.
Example:
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.)
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 < [email protected] > 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.
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.
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:
For the example of CASE statements, each case value should be documented:
case <variable>.
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
*------------------------------------------------------------
-----*
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).
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.
Validation Rules
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 [email protected] 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 [email protected] as early as possible with a minimum of one week
notification before transport to the test and integration system.
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 - IF...ELSEIF...ENDIF :
ENDIF.
Example - AND:
ENDIF.
Example - OR:
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.
is better than
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:
Use this:
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:
• 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:
• use READ TABLE WITH KEY BINARY SEARCH for better performance.
12. SORTing internal tables
SORT ITAB.
LOOP AT ITAB.
CNTLNS = CNTLNS + 1.
ENDLOOP.
To find out the length of a field use the string length function.
ENDIF.
FLDLEN = SY-FDPOS.
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
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.
endform.
Instead of this:
form select_bad.
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.
Use:
where ...
Instead of using:
There are a few cases where one command is better than two. For example:
Use:
Instead of:
<tab> = <tab_wa>.
Instead of:
if <line_counter> > 0.
Use this:
Instead of this:
loop at <tab1>.
endloop.
However, if <tab2> is not empty and should not be overwritten, then use:
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.
* For example, here is a table line type with some vendor fields
or
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.
or
* This example would define a vendor table type sorted by vendor number
* 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.)
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.
Is the program using SELECT * statements?
Convert them to SELECT column1 column2 or use projection views.
Are CHECK statements for table fields embedded in a SELECT ... ENDSELECT loop?
Incorporate the CHECK statements into the WHERE clause of the SELECT statement.
Do SELECTS on non-key fields use an appropriate DB index or is the table buffered?
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.
Is the program using nested SELECTs to retrieve data?
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".
Are there SELECTs without WHERE condition against tables that grow constantly
(BSEG, MKPF, VBAK)?
Program design is wrong - back to the drawing board.
Are SELECT accesses to master data tables buffered (no duplicate accesses with the
same key)?
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
Is the program using SELECT ... APPEND ITAB ... ENDSELECT techniques to fill
internal tables?
Change the processing to read the data immediately into an internal table (SELECT
VBELN AUART ... INTO TABLE T_VBAK ...)
Is the program using SELECT ORDER BY statements?
Data should be read into an internal table first and then sorted unless there is an
appropriate index on the ORDER BY fields
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?
Use the calculation capabilities of the database via SELECT SUM, ...
Are internal tables processed using the READ TABLE itab WITH KEY ... BINARY
SEARCH technique?
Change table accesses to use BINARY SEARCH method
Is the program inserting, updating, or deleting data in dialog mode (not via an
update function module)?
Make sure that the program issues COMMIT WORK statements when one or more
logical units of work (LUWs) have been processed.
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.
ABAP Reports
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
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
Examples:
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 <[email protected] >. See Appendix C for
a list of development classes.
Most SAP system interfaces using flat ASCII files for input or output should use the following
directory paths for temporary and permanent interface files.
end of myfile.
initialization.
importing
func = myfile-part2
exceptions
unknown_sysid = 1
unknown_mandt = 2.
if sy-subrc eq 0.
endif.
Function Groups
Position Usage
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
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
Position Usage
Position Usage
1 'M' as required by the system to denote online modules
6 'I' for PAI modules, 'O' for PBO modules, 'F' for
subroutines
Introduction
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:
The class name should consist of nouns and should only use
Class in Class Library* the
singular form:
ZCL_COMPANY_CODE
ZCL_GENERAL_LEDGER_ACCOUNT
ZIF_<interface name>
Interfaces in
The naming conventions for classes also apply to interface:.
ClassLibrary*
ZIF_STATUS_MANAGEMENT,
ZIF_CHECKER
Types in the DDIC* Z<type name>
LCL_<class name>
The class name should consist of nouns and should only use
Local Class the
singular form:
LCL_TRANSACTION
LIF_<interface name>
The class name should consist of nouns and should only use
Local Interface
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>
Check Methods
Method Conventions
The parameters are observed from the point of view of the methods, which
implemented them:
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
The requested action or the requested OK-Code is not supported
SUPPORTED
This EXCEPTION can be set if the user is required to select what
CANCELLED happens next in a method (for example: Selection List) and he/she selects
"Cancel".
EXISTING A new object already exists in the database.
The methods could not carry out your task because of the present state of
the environment. This exception is especially intended for cases where
FAILED
the environment is temporarily in a situation that does not allow the
method tasks to be carried out.
A sub function of the method could not be carried out because of the
..._FAILED 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.
The object data entered is not correct. (e.g. Company Code is not
INVALID
available) (in contrast to NOT_QUALIFIED)
The given sub-object data of an object is not correct. (In contrast to
..._INVALID
NOT_QUALIFIED)
The last resort. If all else fails and the error can no longer be contained,
INTERNAL_ERROR
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.
The combination of input parameters is not sufficient to allow the
NOT_QUALIFIED
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.
This exception can be set where the Basis System registers an unexpected
SYSTEM_ERROR
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.
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
ABAP: Passing unknown table structures into functions
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.
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:
PART1(3) TYPE N,
PART3(3) TYPE N,
END OF POINTER.
FIELD-SYMBOLS: <INDIRECT>.
POINTER-STEM = STEM.
POINTER-PART1 = SUB1.
POINTER-PART2 = SUB2.
POINTER-PART3 = SUB3.
IF SY-SUBRC <> 0.
ENDIF.
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:
do 224 times.
hex-byte = temp.
char = hex.
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.
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:
data string(20).
data temp(2).
if temp(1) cn '0123456789'.
endif.
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.
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.
DATA: ...
SELECT-OPTIONS: ...
PARAMETERS: ...
FIELD-SYMBOLS: ...
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.
GET ...
END-OF-SELECTION.
SORT ...
LOOP ...
AT FIRST.
ENDAT.
AT NEW ...
ENDAT.
AT END OF ...
ENDAT.
AT LAST.
ENDAT.
ENDLOOP.
* Subroutines
*------------------------------------------------------------
----
*
*
*------------------------------------------------------------
----
FORM ...
ENDFORM.
Interactive ABAP/4 List Report
REPORT ZSKELINT.
*------------------------------------------------------------
----
* Purpose:
*
*
*------------------------------------------------------------
----
* Author:
* Date:
*------------------------------------------------------------
----
* Revision History:
*
*------------------------------------------------------------
----
TABLES: ...
DATA: ...
SELECT-OPTIONS: ...
PARAMETERS: ...
FIELD-SYMBOLS: ...
FIELD-GROUPS: ...
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.
START-OF-SELECTION.
GET ...
END-OF-SELECTION.
SORT ...
LOOP...
WRITE:/ ...
HIDE: ...
ENDLOOP.
AT PF...
AT USER-COMMAND.
CASE SY-UCOMM.
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 ...
END-OF-SELECTION.
* Subroutines
*------------------------------------------------------------
----
*
*
*------------------------------------------------------------
----
FORM ...
ENDFORM.
Read Sequential Dataset and Create a BDC Session
report zskelbdc.
*-----------------------------------------------------
------------
* Purpose:
*
*
*-----------------------------------------------------
------------
* Author:
* Date:
*-----------------------------------------------------
------------
* Revision History:
*
*-----------------------------------------------------
------------
tables: ...
end of t_tab.
select-options: ...
parameters: ...
field-symbols: ...
*-----------------------------------------------------
-----------*
start-of-selection.
if sy-subrc <> 0.
stop.
endif.
skip.
sy-subrc.
*-----------------------------------------------------
-----------*
*-----------------------------------------------------
-----------
* Subroutines *
*-----------------------------------------------------
-----------
*--- Add a line to the DYNPRO Table
----------------------------
clear t_bdcdata.
t_bdcdata-program = program.
t_bdcdata-dynpro = dynpro.
t_bdcdata-dynbegin = 'X'.
append t_bdcdata.
endform.
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, ...
message_text(120).
select-options: ...
parameters: ...
field-symbols: ...
start-of-selection.
*-----------------------------------------------------
-----------*
* Message handling
return_code = sy-subrc.
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.
modify ...
else.
modify ...
endif.
refresh t_trantab.
end-of-selection.
*-----------------------------------------------------
-----------
* Subroutines *
*-----------------------------------------------------
-----------
*--- Add a line to the DYNPRO Table
----------------------------
clear t_bdcdata.
t_bdcdata-program = program.
t_bdcdata-dynpro = dynpro.
t_bdcdata-dynbegin = 'X'.
append t_bdcdata.
endform.
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- Devel. Devel.
Character Application Class- Class-
Abbr. Name MIT Lincoln
Asset
AA ZKG0 .
Accounting
Accounting
AC . .
General
AP Advanced ZAP0 .
Planner and
Optimizer
Accounts
AR ZAR0 .
Receivable
Authorization ZSB0/
AU .
Checks ZR30
Basis
BC . .
Components
BP Buy-Pay ZSC0/ .
Process (incl. ZUT0/
Purchasing) ZSB0
Bridges /
BR ZBR0 .
Infrastructure
Budget
BU ZBUD0 .
(SAPBud)
Business
BW Information . .
Warehouse
CA**
Cashier's Office ZCS0 .
CS
Cross-
CA Application . .
Components
Change
CD . .
Documents
Ckeck Modules
(see the section
on
CK ZUT0 .
"Check Modules
for External
Commands")
CO Controlling ZKG0 .
CS ** Customer
. .
CU Service
Enterprise
Controlling
EC . .
(or Electronic
Commerce)
Environment,
EH Health & ZEH0 .
Safety
Extended
ER Relationship . .
Management
Enterprise
ES ZES0 .
Structure
(MIT) Credit
FC ZCC0 .
Card
Financial
FI ZGL0 .
Accounting
Human
HR ZHR0 .
Resources
Investment
IM . .
Management
Industry-
IS Specific . .
Components
SAP Knowledge
KM . .
Management
Labor
L* Distribution ZLD0 .
System
Logistics
LE . .
Execution
Logistics -
LO . .
General
Materials
MM . .
Management
mySAP.com
MP . .
Marketplace
MS Mobile Sales . .
Personnel
PA . .
Management
Training and
PE Event ZPE0 .
Management
Plant
PM ZPM0 ZLCP1_PM0
Maintenance
Production
Planning and
PP Control ZPP0 .
(or Physical
Plant)
Personnel Time
PT . .
Management
Payroll
PY ZPY0 .
Accounting
Quality
QM . .
Management
Real Estate
RE ZRE0 .
Management
RQ Requisitions . .
Sales and
SD ZSB0 .
Distribution
Strategic
SE Enterprise . .
Management
SV Service . .
TR **
Treasury . .
TY
TR Travel ZTR0 .
Time Sheet
TS . .
(CATS Related)
Utilities and
UT ZUT0 .
Tools
WF Workflow ZWF0 .
(MIT) Data
WH ZWH0 .
Warehouse
WP mySAP.com . .
Workplace
XX Miscellaneous . .
IMG
. ZLCP1_IMG
Documentation
** should NOT be used for new programs created after October 1, 2001.
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 < [email protected] > regarding the creation
of new development classes or the uses of existing classes.
DEVEL.
DESCRIPTION
CLASS
Notes:
• The development class Z001 is an SAP example and it should not be used to classify MIT
objects.
• The Development classes ZBR1, ZGN0, and ZSPO are obsolete and should not be used
to classify any new development object.
• The Development classes ZWB0 and ZWB1 are meant to be specific to objects related to
MIT's ABAP workshops. Such objects should not be transported into our test, production,
or training environments.
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.