[go: up one dir, main page]

0% found this document useful (0 votes)
482 views25 pages

Sap Abap Naming Conventions

Naming conventions lend consistency and readability to code, improving maintainability. This document outlines naming standard recommendations for various program objects and variables, including classes, constants, data elements, internal tables, parameters, and events. It also provides naming standards for interface parameters in functions and methods, with importing, exporting, changing, and returning parameters all prefixed with identifiers like IM_, EX_, and CH_.

Uploaded by

karthik_spic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
482 views25 pages

Sap Abap Naming Conventions

Naming conventions lend consistency and readability to code, improving maintainability. This document outlines naming standard recommendations for various program objects and variables, including classes, constants, data elements, internal tables, parameters, and events. It also provides naming standards for interface parameters in functions and methods, with importing, exporting, changing, and returning parameters all prefixed with identifiers like IM_, EX_, and CH_.

Uploaded by

karthik_spic
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

TYPES

Simple type definition


- TYPES type.
- TYPES type(len).

Definition of a structured type


- TYPES: BEGIN OF structype
...
END OF structype.

Definition of an internal table type


- TYPES itabtype {TYPE tabkind OF linetype|
LIKE tabkind OF lineobj}
[WITH [UNIQUE|NON-UNIQUE] keydef] [INITIAL SIZE n].
- TYPES itabtype {TYPE RANGE OF type|TYPES itabtype LIKE RANGE OF
f}.
- TYPES itabtype {TYPE linetype|LIKE lineobj} OCCURS n.

Type Description DL Initial value

C Character 1 Space
N Numeric text 1 '00...0'
D Date YYYYMMDD 8 '00000000'
T Time HHMMSS 6 '000000'
X Byte (heXadecimal) 1 X'00'
I Integer 4 0
P Packed number 8 0
F Floating point number 8 '0.0'
STRING String variable empty string
XSTRING Byte sequence (X string) variable empty X string

The system field SY-DBCNT contains the number of lines read so far ecah time the
SELECT statement is executed. After ENDSELECT, SY-DBCNT contains the total
number of records read.

The Return Code is set as follows:


SY-SUBRC = 0:
The result table contains at least one record.
SY-SUBRC = 4:
The result table is empty.
SY-SUBRC = 8:
Applies only to SELECT SINGLE FOR UPDATE: You did not specify all of the primary key
fields in the WHERE condition. The result table is empty.

Dictionary Objects

DDIC Object Naming Standard Repository Meta Data


Entry Table

Domain Z*
Data Element Z*
Lock Object EZ*
Search Help ZSH*
Structure ZS*
Table Z* or ZT*
Table Type Z* or ZTY*
Table Indeces Z## 3 character unique name
Type Group ZTG*
View ZV*

Sample Program Types

R - Report
D - Data Load
I - Include
X - Interface
etc.

SAP Object Naming Standard Repository Entry Meta Data


Table

Application Log Z*
Area Menu Z*
Batch Input Session Z*
Change Document Z*
Package Z*
Dialog Module Z*
CMOD Enhancement Z*
Project
Form Pool SAPFZ*

Generated Include modules


should follow SAP suggested
recommendations

For Example
FZ*TOP - Data declarations
FZ*F## - Subroutines
Function Groups Z*
Function Modules Z_*
Gui Status Z*
Include ZI*
Memory ID ZM*
Message Class Z*
Messages Number numeric 3 digits 1-999
Module Pool SAPMZ*

Generated Include modules


should follow SAP suggested
recommendations

For Example
MZ*TOP - Data declarations
MZ*O## - PBO modules
MZ*I## - PAI modules
MZ*F## - Subroutines
Number Range ZNR*
Program Ztype* where type identifies the program
function
Screen 4 characters
GUI Title Z*
Transaction Code Z*

Naming Conventions
Naming Conventions lend consistency and readabilty to your code. This in turn improves the overall maintainability of
code. When naming your objects and variables, try to avoid arcane acronyms. Spell it out where possible.

Refer to the table below for accepted industry standard naming conventions for objects and variables within a program.

Program Internal Objects Convention Example


Class - local lcl_* lcl_salesorder
Class - Interface lif_* lif_salesorder
Constant c_* or co_* c_open_indicator
Data Reference dr_* dr_openorder
Data Variables - Global v_* or gv_* v_order
Data Variables - Local lv_* lv_order
Data Variables - Static lsv_* lsv_order
Field Symbols <fs_*> <fs_order>
Internal Table - Standard t_* t_orders
Internal Table - Sorted ts_* or to_* ts_orders
Internal Table - Hashed th_* th_orders
Parameters pa_* pa_order

Ranges ra_* ra_orders


Reference Variable rf_* rf_orders
Select-Options so_* so_date
Structure st_* or w_* st_orders
Table Control tc_* tc_orderlines
Types ty_* ty_ordertype
Work Area w_* w_order

Interface Parameters
Subroutine Formal Parameters Convention Example
Using u_* or p_*
Changing c_* or p_*
Raising r_* or p_*

Method Signature Convention Example


Importing im_*
Exporting ex_*
Changing ch_*
Returning re_*
Raising cx_* for exception classes
Exceptions not applicable

Function Interface Convention Example


Importing im_*
Exporting ex_*
Changing ch_*
Tables t_*
Exceptions not applicable
Raising not applicable

Functions/Methods
FUNCTIONS

Use the built in documentation features found in SE37 to document the purpose of the function modules and the usage
of the Interface parameters.
The use of naming standards for interface parameters is not a common practice, although it should be so SAPdomain
recommends the following:

Importing Parameters: IM_*


Exporting Parameters: EX_*
Changing Parameters: CH_*
Tables Parameters: TB_*

METHODS

For Methods Use the Following naming standard for the signature of the method.

Importing: IM_*
Exporting: EX_*
Changing : CH_*
Returning: RE_*
Raising: exception (no std)
Exceptions: exception_class (no std)
Events
List Processing Events are executed in a predefined order according to the rules of the ABAP interpreter and therefore
the order in which they appear in an ABAP program is not important. However there is a standard practice among
programmers (for readability) to order events according to the order of execution.

It is good practice to identify events with a comment banner. i.e.

List Processing Events


Guidelines by Topic
Error Handling General Maintainability
Functions Incomplete Code Clever coding
Methods Incorrect Usage Code Encapsulation
Message Types - A E X I Multi-lingual Hard Coding
WS Obsolete ABAP Modularization
Return Code Checking Statements ">Obsolete Sloppy
SQL Other Standards

Performance Processing Stability


Internal Table Internal Tables Address and Memory
SQL Output Pointers
Other Selecting Data Dynamic Programming
Updates Handling Program
Dumps

Error Handling

Exception Handling – Checking Return Codes


Guideline: Always Check Return Code after critical operations – SQL, ITAB Operations, Function Calls, etc.
Explanation: "this code will never fail", "it will always return data"
Have you heard this before ?

This guideline is the single most overlooked coding practice by developers but yet one of the most
critical techniques available that ensures fail safe programming that avoids potential failure points.

Never make an assumption that a piece of code will always work. By putting in proper subrc checking,
your program is assured that it can at least handle erroneous situations. Fail safe programming is
critical to quality applications.

The programmer should always, at minimum, put in a generic 'catch-all' check that will catch any failed
condition. More specific checks can always be added.

Proper message issuing and exception processing makes for a program that is easy to support and
maintain. It is a key component of quality programming. It is also a tell tale sign of the skill, experience,
and attitude of a developer towards quality programming.

Snippet:

after any SQL, ITAB Operations, Function Calls, etc.

IF sy-subrc = 0.
code.
Else.
* no code
ENDIF.

OR
IF sy-subrc = 0.
code for successful operation only
ENDIF.

* Programmer should always code for the failed


condition. In this case, they did not code for a non zero
subrc.

after any SQL, ITAB Operations, Function Calls, etc.

IF sy-subrc = 0.
code.
Else.
code.
ENDIF.

Or
IF sy-subrc <> 0.
code.
ENDIF.

OR
When no action is required after a non zero code, then
simply add a comment. This at least indicates that the programmer gave
some thought to the outcome of a failed condition which in some cases is
OK to continue processing.
Sample comment:
* non zero return code is OK. Continue processing

Exception Handling - after function call


Guideline: Generic Messaging after a function call is not recommended.
Explanation: Anytime you use the PATTERN function in the workbench to insert a function, it automatically inserts a
generic message in the format

“MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2, sy-msgv3, sy-
msgv4”.

This statement assumes that SY variables have been filled with meaningful values by the function itself.
However, often times, this is not the case.

The generic message should only be used in the case where the function and all nested functions that
are called use the Message...Raising format consistently throughout the function chain. The
Message...Raising format sets the sy-message and other sy variables. Only then, can you be assured
that a generic message statement can be used to present a proper error message. However, since this
situation is most likely not the case, a good developer will handle the message themselves and not
count on the generic form to provide a meaningful message relevant to the situation.

Snippet:

IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty
NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.
CALL FUNCTION 'Z_MATERIAL_VIEW'
EXPORTING
im_full_details = 'X'
im_t_material = t_materials
EXCEPTIONS
invalid_input = 1
invalid_material = 2
no_materials = 3
OTHERS = 4.

CASE sy-subrc.
WHEN 1.
MESSAGE e999 WITH 'Invalid Input'(101).
WHEN 2.
MESSAGE e999 WITH 'Invalid Material'(102).
WHEN 3.
MESSAGE e999 WITH 'No Materials'(103).
WHEN 4.
MESSAGE e999 WITH 'Other Reasons'(104).
ENDCASE.

Message Processing
Guideline: Use the correct message type A,E,X,W,I,S to determine the expected outcome
Explanation: When issuing error messages, the flow of the program may take different paths based on the message
type and the context in which the message is issued.

SAP online Help provides a good explanantion of the message types and the program reaction
depending where in a processing block the message is issued.
For Example
- An 'S' message reacts differently in an AT event than it does when issued in a FORM.
- An 'E' Message in the At Selection Screen Event will require the user to re-enter the input whereas a
W message is simply a warning and the user only needs to press ENTER to bypass the warning
condition so that program processing can resume.

Suggestion: Messages in all events need to be evaluated to determine if there is a reason to stop the
program with an E type message or have it continue processing.

Executable programs should always allow the user the option to exit or correct an error situation, for
example in a selection Screen. That’s why E and W messages need to be used with knowledge of the
outcome. TEST the situation thoroughly if you are unsure and then TEST again even if you are sure.

In Background Jobs, when a program is executed in the background, a message issued of type ‘E’, ‘A’
or ‘X’ will cancel the execution of the job. The job log is a handy feature to determine status of a job.
Messages issued in background show up in the job log so be sure to provide meaningful messages that
will easily identify the point of failure and course of action required.

If an online program is executed in background, the messaging can be bypassed by first checking to
see if it is running in background by evaluating the sy-batch variable. If the program is running in
background, then do not issue error messages that would typically be used to interact with the user.

For Online Selection Screen type programs - use the Write statement to issue the message to output
and then issue a type S message and then a Leave List-Processing statement should follow this. This
returns the user back to the selection screen.
Snippet:

under construction
Functions

Exception Handling - after function call


Guideline: Generic Messaging after a function call is not recommended.
Explanation: Anytime you use the PATTERN function in the workbench to insert a function, it automatically inserts a
generic message in the format

“MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2, sy-msgv3, sy-
msgv4”.

This statement assumes that SY variables have been filled with meaningful values by the function itself.
However, often times, this is not the case.

The generic message should only be used in the case where the function and all nested functions that
are called use the Message...Raising format consistently throughout the function chain. The
Message...Raising format sets the sy-message and other sy variables. Only then, can you be assured
that a generic message statement can be used to present a proper error message. However, since this
situation is most likely not the case, a good developer will handle the message themselves and not
count on the generic form to provide a meaningful message relevant to the situation.

Snippet:

IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty
NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.

CALL FUNCTION 'Z_MATERIAL_VIEW'


EXPORTING
im_full_details = 'X'
im_t_material = t_materials
EXCEPTIONS
invalid_input = 1
invalid_material = 2
no_materials = 3
OTHERS = 4.

CASE sy-subrc.
WHEN 1.
MESSAGE e999 WITH 'Invalid Input'(101).
WHEN 2.
MESSAGE e999 WITH 'Invalid Material'(102).
WHEN 3.
MESSAGE e999 WITH 'No Materials'(103).
WHEN 4.
MESSAGE e999 WITH 'Other Reasons'(104).
ENDCASE.
Message Types - A E X I W S

Message Processing
Guideline: Use the correct message type A,E,X,W,I,S to determine the expected outcome
Explanation: When issuing error messages, the flow of the program may take different paths based on the message
type and the context in which the message is issued.

SAP online Help provides a good explanantion of the message types and the program reaction
depending where in a processing block the message is issued.
For Example
- An 'S' message reacts differently in an AT event than it does when issued in a FORM.
- An 'E' Message in the At Selection Screen Event will require the user to re-enter the input whereas a
W message is simply a warning and the user only needs to press ENTER to bypass the warning
condition so that program processing can resume.

Suggestion: Messages in all events need to be evaluated to determine if there is a reason to stop the
program with an E type message or have it continue processing.

Executable programs should always allow the user the option to exit or correct an error situation, for
example in a selection Screen. That’s why E and W messages need to be used with knowledge of the
outcome. TEST the situation thoroughly if you are unsure and then TEST again even if you are sure.

In Background Jobs, when a program is executed in the background, a message issued of type ‘E’, ‘A’
or ‘X’ will cancel the execution of the job. The job log is a handy feature to determine status of a job.
Messages issued in background show up in the job log so be sure to provide meaningful messages that
will easily identify the point of failure and course of action required.

If an online program is executed in background, the messaging can be bypassed by first checking to
see if it is running in background by evaluating the sy-batch variable. If the program is running in
background, then do not issue error messages that would typically be used to interact with the user.

For Online Selection Screen type programs - use the Write statement to issue the message to output
and then issue a type S message and then a Leave List-Processing statement should follow this. This
returns the user back to the selection screen.

Return Code Checking

Exception Handling – Checking Return Codes


Guideline: Always Check Return Code after critical operations – SQL, ITAB Operations, Function Calls, etc.
Explanation: "this code will never fail", "it will always return data"
Have you heard this before ?

This guideline is the single most overlooked coding practice by developers but yet one of the most
critical techniques available that ensures fail safe programming that avoids potential failure points.

Never make an assumption that a piece of code will always work. By putting in proper subrc checking,
your program is assured that it can at least handle erroneous situations. Fail safe programming is
critical to quality applications.

The programmer should always, at minimum, put in a generic 'catch-all' check that will catch any failed
condition. More specific checks can always be added.
Proper message issuing and exception processing makes for a program that is easy to support and
maintain. It is a key component of quality programming. It is also a tell tale sign of the skill, experience,
and attitude of a developer towards quality programming.

Snippet:

after any SQL, ITAB Operations, Function Calls, etc.

IF sy-subrc = 0.
code.
Else.
* no code
ENDIF.

OR
IF sy-subrc = 0.
code for successful operation only
ENDIF.

* Programmer should always code for the failed


condition. In this case, they did not code for a non zero
subrc.

after any SQL, ITAB Operations, Function Calls, etc.

IF sy-subrc = 0.
code.
Else.
code.
ENDIF.

Or
IF sy-subrc <> 0.
code.
ENDIF.

OR
When no action is required after a non zero code, then
simply add a comment. This at least indicates that the programmer gave
some thought to the outcome of a failed condition which in some cases is
OK to continue processing.
Sample comment:
* non zero return code is OK. Continue processing

Performance
Performance desc

SELECT vs. VIEW


Guideline: Use views where possible over multiple table selects
Explanation: VIEWs can make programs more readable.
VIEW improve performance.
Views can be buffered.

Use SAP standard VIEWs instead of creating new VIEWs if possible.

Internal Tables - Reading a Standard Table


Guideline: When using READ on a standard table, always perform a Sort by and Delete adjacent Duplicates
before performing the READ and always use the Binary Search option i.e. READ itab with KEY...Binary
Search
Explanation: Table should be sorted by sorting keys to take advantage of Binary Search. If you sort by one key and
Read with a different set, you could miss data.

Internal Tables should always be sorted before using DELETE ADJACENT DUPLICATES. Delete
Adjacent Duplicates should always be explicit by using the COMPARING Clause, even if there is only
one field in the itab.

When sorting internal tables, always use explicit sort keys i.e. use "SORT BY Key1...n", never just
"SORT" on it's own. Not following this practice could lead to unexpected situations if the structure of the
table changes.

Keeping the "SORT itab BY" statement as close as possible to the READ itab with KEY...Binary Search
is a good coding practice.

Snippet:

SORT T_DOCUMENT.
DELETE ADJACENT DUPLICATES FROM T_DOCUMENT.

SORT T_DOCUMENT BY VBELN VBELP.


DELETE ADJACENT DUPLICATES FROM T_DOCUMENT COMPARING VBELN VBELP.
General

Constants
Guideline: Use Keyword CONSTANT for variables that do not change rather than using the DATA Keyword
Explanation: Defining a variable as a constant prevents anyone from changing the value of the constant especially
when the program gets maintained in the future. This guarantees that the value can never be changed
and potentially alter the outcome of the program.
Snippet:

DATA: v_switch(1) type c value “X”

CONSTANTS: v_switch(1) TYPE C value ‘X’.

Data Objects - Use of Type


Guideline: Avoid using the keyword 'like' when typing a data object
Explanation: Data Definitions should use the ‘TYPE’ keyword to define it’s data type. LIKE is an old convention that is
no longer encouraged and only exists for backwards compatibility. When programming in ABAP OO,
LIKE is not allowed when referencing dictionary objects.
Snippet:

DATA: V_ORDER LIKE VBAK-VBELN.

DATA: V_ORDER TYPE VBAK-VBELN.

On Change of
Guideline: Avoid using On Change Of statement for Break processing
Explanation: For Internal table Loop processing, break level processing should be programmed with the AT....ENDAT
statements. Do not use ON CHANGE OF because it is specific to a single field. Unpredictable results
can occur with the ON CHANGE OF, whereas the AT... ENDAT triggers a break when any change
occurs in the specified field or fields left of the specified field.
Snippet:

ON CHANGE OF.

AT…ENDAT.

Case versus IF
Guideline: For Multiple conditions, use CASE
Explanation: Use the CASE statement rather than IF/ELSEIF/ENDIF statement when there are multiple conditions. If
there is only one condition, then the IF/ELSE/ENDIF statement is a good choice.
Snippet:

IF SY-SUBRC = 1.
code 1.
ELSEIF SY-SUBRC = 2.
code 2.
ELSE.
code others.
ENDIF.

CASE SY-SUBRC.
WHEN 1.
code 1.
WHEN 2.
code 2.
WHEN OTHERS.
code others.
ENDCASE.

Interrupt Commands – CHECK, EXIT, STOP, LEAVE, RETURN


Guideline: Always Test positive and negative conditions for interrupt commands to ensure the code branches down
the intended path
Explanation: Interrupt commands react according to the rules of the command in conjunction with the type of code
that encapsulates them. It is heavily suggested to consult your help guides on the statement used and
the placement of the statement as to the expected outcome when/if the interrupt command is executed.
When using interrupt type commands such as CHECK, EXIT, LEAVE, the programmer should thoroughly
test the condition to ensure the code branches down the intended path to ensure that any required
follow-on processing is actually executed.
i.e. A failed CHECK statement in a LOOP, SELECT, EVENT, FORM, GET, etc. all react differently to the
check COMMAND. This is also true for the EXIT statement in a LOOP, SELECT, EVENT, FORM, GET,
etc.

Caution: DO NOT place a CHECK or EXIT statement in a user exit. If the CHECK or EXIT statement is
executed, all following user exits will not be executed.

In Summary: Use the correct Interrupt command to ensure the logic flow takes the path expected.
Snippet:

under construction

File Operations - Open


Guideline: Use the MESSAGE keyword on the OPEN statement to trap operating system errors
Explanation: Always include the MESSAGE keyword on the OPEN statement to trap operating system errors. Subrc
only tells if the operation was successful or not. The MESSAGE keyword provides for more specific
application server errors such as permissions, file existence, etc.
Snippet:

DATA: V_MSG(100) Type C.


OPEN DATASET V_INPUT_FILE FOR INPUT MESSAGE V_MSG.
IF SY-SUBRC <> 0.
write E100.
ENDIF.

DATA: V_MSG(100) Type C.


OPEN DATASET V_INPUT_FILE FOR INPUT MESSAGE V_MSG.
IF SY-SUBRC <> 0.
write E100 with
v_msg sy-subrc sy-uname sy-cprog.
ENDIF.

The above message will produce the following message:


“Program Z_progxxx run by Joe Smith failed with ‘file permissions’ problem,
RC=4”.

File Operations - logical file names


Guideline: Use Logical Filenames for processing external files
Explanation: All input and output file names must be passed to the program as parameters using logical file names.
Logical filenames are mapped to physical filenames using transaction FILE. When possible, logical file
names should be included in the selection screen of the program. The function FILE_GET_NAME must
be used to translate the logical file name to the physical path and file name. If you are the person
creating logical file names, it is advised that you use the logical paths and dynamic variables i.e. client,
instance, etc. to ensure file names meet your file naming conventions and the programs that use the files
work across all system boundaries.
Snippet:

under construction
Exception Handling - after function call
Guideline: Generic Messaging after a function call is not recommended.
Explanation: Anytime you use the PATTERN function in the workbench to insert a function, it automatically inserts a
generic message in the format

“MESSAGE ID sy-msgid TYPE sy-msgty NUMBER sy-msgno WITH sy-msgv1 sy-msgv2, sy-msgv3, sy-
msgv4”.

This statement assumes that SY variables have been filled with meaningful values by the function itself.
However, often times, this is not the case.

The generic message should only be used in the case where the function and all nested functions that
are called use the Message...Raising format consistently throughout the function chain. The
Message...Raising format sets the sy-message and other sy variables. Only then, can you be assured
that a generic message statement can be used to present a proper error message. However, since this
situation is most likely not the case, a good developer will handle the message themselves and not count
on the generic form to provide a meaningful message relevant to the situation.

Snippet:

IF sy-subrc <> 0.
MESSAGE ID sy-msgid TYPE sy-msgty
NUMBER sy-msgno
WITH sy-msgv1 sy-msgv2 sy-msgv3 sy-msgv4.
ENDIF.

CALL FUNCTION 'Z_MATERIAL_VIEW'


EXPORTING
im_full_details = 'X'
im_t_material = t_materials
EXCEPTIONS
invalid_input = 1
invalid_material = 2
no_materials = 3
OTHERS = 4.

CASE sy-subrc.
WHEN 1.
MESSAGE e999 WITH 'Invalid Input'(101).
WHEN 2.
MESSAGE e999 WITH 'Invalid Material'(102).
WHEN 3.
MESSAGE e999 WITH 'No Materials'(103).
WHEN 4.
MESSAGE e999 WITH 'Other Reasons'(104).
ENDCASE.

Open - Message Clause


Guideline: Use Message clause on OPEN statement to trap operating system errors.
Explanation: Authorization and permission access at the OS level is one of the most frequent causes of an OPEN
statement failing. Checking the sy-subrc will only indicate that the operation failed but not the reason
why. To trap the error condition at the operating system level, Use the Message option on the Open
command.
Snippet:

OPEN DATASET V_INPUT_FILE FOR INPUT.


IF SY-SUBRC <> 0.
write sy-subrc.
ENDIF.

DATA: V_MSG(100) Type C.

OPEN DATASET V_INPUT_FILE FOR INPUT MESSAGE V_MSG.

IF SY-SUBRC <> 0.
write E100 with v_msg sy-subrc.
ENDIF.

Subscripting and Offsets


Guideline: Avoid code that uses specific offsets for the purpose of subscripting into fields and structures
Explanation: Avoid code that uses specific offsets to subscript into the code. Try to determine lengths and use
structures to achieve positioning of fields. This is especially vulnerable when coding in a UNICODE
environment as characters are not represented by a single byte.
Snippet:

Date is often times subscripted


The following code is sensitive to the user master record and vulnerable to
subscripting errors.
V_YEAR = V_MYDATE+4(4).
V_MONTH = V_MYDATE+2(2).
V_DAY = V_MYDATE+0(2).

This code is longer, yes, but not sensitive to date format changes which
can cause some very serious errors and outcome.

BEGIN OF S_MYDATE,
MONTH(2),
DAY(2),
YEAR(4),
END OF S_MYDATE .

BEGIN OF S_YOURDATE,
YEAR(4),
MONTH(2),
DAY(2),
END OF S_YOURDATE.

S_MYDATE-YEAR = S_YOURDATE-YEAR.
S_MYDATE-MONTH = S_YOURDATE-MONTH.
S_MYDATE-DAY = S_YOURDATE-DAY.

Internal Tables - Defining


Guideline: Do not use Occurs 0 or With Header Line unless it is a SAP function that requires it.
Explanation: STRUCTURE and "TABLES" clause is considered obsolete. If your internal table is a custom structure,
always declare the table structure within a type statement before defining the internal table itself.
Snippet:

DATA: BEGIN OF T_MAT OCCURS 0,


MATNR LIKE MARA-MATNR,
WERKS LIKE MARC-WERKS,
DISPO LIKE MARC-DISPO,
END OF T_MAT.
TYPES: BEGIN OF TYPE_MAT,
MATNR LIKE MARA-MATNR,
WERKS LIKE MARC-WERKS,
DISPO LIKE MARC-DISPO,
END OF TYPE_MAT.

DATA: T_MAT TYPE STANDARD TABLE OF TYPE_MAT.

Structures

Simple Structure Example


Data: BEGIN OF S_ORDER.
INCLUDE STRUCTURE VBAK.
Data: END OF S_SORDER.

Simple Structure Example

DATA: S_ORDER TYPE VBAK.

Deep Structure

Data: BEGIN OF S_ORDER,


component1,
Include Structure VBAK
component2,
Data: END OF S_ORDER

Deep Structure
Data: BEGIN OF S_ORDER,
component1(1) type c,
component2 TYPE VBAK,
component3 type I,
Data: END OF S_ORDER.

Special Considerations:
To access the individual fields in a deep structure, please use syntax in the following example
S_ORDER-S_SO-VBELN = v_ordernumber.

Typing Structures

TYPES: BEGIN OF TYPE_MYSTRU.


INCLUDE STRUCTURE VBAK.
TYPES: v_po_doc LIKE EKPO-VBELN,
END OF TYPE_MYSTRU.

Typing Structures

TYPES: BEGIN OF TYPE_MYSTRU,


s_so TYPE VBAK,
v_po_doc TYPE EKPO-VBELN,
END OF TYPE_MYSTRU.

TABLES
Guideline: TABLES statement is not required
Explanation: The use of TABLES statements for the declaration of work areas or when used in an SQL statement, is
not required. It allocates unnecessary storage. This is a pre 4.x convention
Snippet:

TABLES: EKPO.

TABLES statement not required

Internal Tables - Defining


Guideline: Do not use Occurs 0 or With Header Line unless it is a SAP function that requires it.
Explanation: STRUCTURE and "TABLES" clause is considered obsolete. If your internal table is a custom structure,
always declare the table structure within a type statement before defining the internal table itself.
Snippet:

DATA: BEGIN OF T_MAT OCCURS 0,


MATNR LIKE MARA-MATNR,
WERKS LIKE MARC-WERKS,
DISPO LIKE MARC-DISPO,
END OF T_MAT.

TYPES: BEGIN OF TYPE_MAT,


MATNR LIKE MARA-MATNR,
WERKS LIKE MARC-WERKS,
DISPO LIKE MARC-DISPO,
END OF TYPE_MAT.

DATA: T_MAT TYPE STANDARD TABLE OF TYPE_MAT.

Internal Tables - Loop into work area


Guideline: Loop at itab should always use a work area or assign to a field symbol
Explanation: Use of internal tables 'with header' is considered an old convention. Internal tables with Header are not
allowed in ABAP OO and will therefore not pass syntax check.

Always use a work area or assign directly to a field symbol when processing the internal table.
Snippet:

Loop at itab.
* reference itab components directly via the header area
result = itab-field1.
Endloop.

Loop at itab into s_itab.


* reference itab components using work area s_itab
result = s_itab-field1.
Endloop.

Loop at itab.
* reference itab components directly via the header area
result = itab-field1.
Endloop.

Loop at itab assigning <fs_itab>.


* reference itab components using field symbol <fs_itab>
result = <fs_itab>-field1.
Endloop.

EXTRACT files
Guideline: Combine multiple arrays of data with different structures into a single table for processing, an EXTRACT
file is an option
Explanation: There are advantages to using an Extract file but common practice is that most developers will tend to
use internal tables for array processing. It is a good option to use for reporting purposes when dealing
with internal tables of different structures that same same or similar keys.

Consideration: From a maintenance perspective, few developers have experience with EXTRACT files.

NOTE: Only one EXTRACT file can be used per program, whereas many internal tables could be used in
one program. There is no right or wrong on this one and is entirely up to the IT shop or the programming
requirement.

Boolean Operators
Guideline: Use operators (+, -, *, /, =) rather than the words ADD, SUBTRACT, MULTIPLY, DIVIDE, MOVE
Explanation: Use the Boolean operators rather than the alphabetic acronyms for boolean operations.

Note: This is not a strict and hard guideline. It is only meant to be a suggestion to adhere to boolean
operations over Engligh like commands.
Snippet:

multiply items by price giving totalprice


totalprice = items * price

Move value1 to value2.

value2 = value1.

IF items GT 0.

IF items > 0.

Functions - Shared Memory


Guideline: Customer Functions that are truly standalone should not share their function group
Explanation: Functions within the same Function Group share a global memory area. When a program calls a
Function Module, all the Function Modules within that group are loaded into memory within the same
logical unit of work. This reduces system overhead by allowing the sharing of global data. In the case,
where a Function Module is truly a standalone object that has no need to share the global resources of a
Function Group, it is recommended that a function group is created to contain only the standalone
function.

Dynamically called Function Modules must be defined in their own Function Group.

If Function Modules are being called ‘IN UPDATE TASK’ and are using internal tables that are defined as
Global Data, the global internal table will need to be cleared each time the function module is being
executed. Otherwise the internal table records are still available from the last function module execution
and could cause failures such as a "Duplicate Key Update Task".
Snippet:

under construction

Data - Global versus local


Guideline: Variables that are only used locally should be defined locally
Explanation: Variables that are used only within a processing unit such as a subroutine should be defined locally
within that processing unit.
Snippet:

data: gv_total type i.

perform calculate_difference.

FORM calculate_difference.
data: lv_amt type i,
lv_raise type i.

gv_total = lv_amt + lv_raise.


write gv_total.
ENDFORM.
perform calculate_difference.

FORM calculate_difference.
data: lv_amt type i,
lv_raise type i,
lv_total type i.

lv_total = lv_amt + lv_raise.


write lv_total.
ENDFORM

Number Ranges
Guideline: Use the number range functions for generating unique sequence numbers
Explanation: A unique sequence number can be auto generated by SAP functionality. No need to build custom
sequence number generators. Use the SAP functions from function groups SNR* for this purpose.

Note: Number range objects are transportable objects but Never transport number range intervals.
Snippet:

ZSEQNO = ZSEQNO + 1.

CALL FUNCTION 'NUMBER_GET_NXT'


EXPORTING
nr_range_nr = '01'
object = 'ZSEQNO'
QUANTITY = '1'
IMPORTING
number = zim_seqno
EXCEPTIONS
OTHERS = 1.

Variant
Guideline: Transporting Variants
Explanation: Variants should be entered in a Gold client and then tranported thru the migration path to the target
environments.

Data Objects - Use of Defaults


Guideline: Do not use implied defaults on data declarations
Explanation: If a field is TYPE C, then be explicit and say Type C. Many programmers are conversant in several
programming languages. By being explicit with variable definitions, it makes it clear for the developer and
leaves no option for interpretation. Defaults are prone to change , especially as the protocols of Unicode
and ABAP OO mature. If defaults change, the outcome of a program can also be affected.
Snippet:

DATA: v_myfield.

DATA: v_myfield(1) TYPE C.


Case - When Others
Guideline: Always program a When Others statement
Explanation: Always program a When Others statement so that any condition that is not met will have a fallout path for
the code to take.

Always provide an action or a generic message so that the program can announce that an unexpected
situation has been encountered.

Snippet:

CASE SY-SUBRC.
WHEN 1.
code 1.
WHEN 2.
code 2.
ENDCASE.

CASE SY-SUBRC.
WHEN 1.
code 1.
WHEN 2.
code 2.
WHEN OTHERS.
MESSAGE W100.
ENDCASE.

Text Elements
Guideline: For multi-lingual prgramming, all text in quotes should have an associated text element defined
Explanation: Think Multilingual

If text literals are enclosed in quotes in statements like WRITE, MESSAGE, CONCATENATE , then there
should be an associated text element.
i.e. Write: "Error with this statement"(099)

Some General Rules

- Do not use multiple text elements to generate one large text within your program.
- Use the addition 'AS TEXT' within SORT statements to ensure that the sort sequence considers
language specific characters, e.g. German ä, ü, ö, β .
- Use Text elements or report title to define list headings
- Text descriptions in the Data Dictionary should be defined in language dependent tables.
- Description fields defined in the Data Dictionary should be long enough to store translations.
Snippet:

Write Text-099

or

Write 'Error with this statement'.

Write: 'Error with this statement'(099).

BAPI
De SAP ABAP en castellano

Saltar a navegación, búsqueda


(Business Application Programming Interfaces). Son funciones que nos
permiten simular funcionalidad. Crear pedido, hacer movimientos de
mercancias, etc.. Normalmente veo lo que hace la transacción estandar, veo
los valores que se van rellenando e intento buscar su correspondencia en la
bapi en los importing o tables.. Es un forma muy simple de verlas, pero es una
introducción simple. Son funcicones que están integradas en los BOR ( objetos
de negocios )..
BAPI viene de un viejo concepto de programación, API, que son programas ya
hechos que están a disposición del programador. En el caso de SAP, las BAPI
son funciones para un determinado uso. Están bastante bien documentadas,
algunas, en la transacción BAPI. Su uso es variado, como ejemplo la creación
de órdenes de compra, por caso. O sea, reemplazando la ejecución de un
CALL TRANSACTION por la BAPI correspondiente. Tiene una mejor
performance, mucha simplicidad en el código y mayor control sobre los datos.
Tienen, también, la particularidad de ser RFC, o sea que se pueden ejecutar en
forma remota desde otro aplicativo. En general, casi todas, están precedidas
por la palabra BAPI. Desde la SE37, tipeando BAPI* y presionando F4 trae el
listado.
Obtenido de "http://sap4.com/wiki/index.php?title=BAPI"

RFC
De SAP ABAP en castellano

Saltar a navegación, búsqueda


Una RFC solo es una función que se puede llamar desde un sistema externo a
SAP, el cual puede ser otro SAP u otro tipo de sistema. Vamos que se definen
en la SE37 igualmente con la diferencia de que en la pestaña de atributos se
pincha el radiobutton "Modulo de acceso remoto". Las aplicaciones de una RFC
si que son mas extensas, pero vamos, que por ejemplo, permiten intercambiar
datos entre SAP y el sistema llamante...infinidad de cosas.
Has de mucho cuidado es con los destinos RFC (transacción SM59) y los
usuarios que están ligados a ellos. Hay varios tipos de usuarios, y normalmente
el que se utiliza para pasar información es el CPIC (lo puedes ver por la
transacción SU01 y la pestaña logon data). Has de tener en cuenta que el
usuario CPIC no pide logon, porque sólo se pasa información, pero si el usuario
es DIALOG pide pantalla de logon y normalmente se utiliza para pasar
pantallas, o sea, conectarse en remoto a una transacción. En teoria este tema
lo gestionan los de sistemas, que se encargan de crear los destinos y los
usuarios asociados a ellos, por lo que para tí debería ser transparente. Por lo
demás, es una función como cualquier otra, y si la llaman desdel exterior de
SAP, mientras le pasen los parámetros correctamente, no hay problema.
Espero que te sirva de ayuda hasta que alguien te pase la documentación.
Ver ejemplo de RFC desde Visual Basic
Obtenido de "http://sap4.com/wiki/index.php?title=RFC"

You might also like