Beruflich Dokumente
Kultur Dokumente
- internal subroutines
- external subroutines
- function m odules
Calling and defining subroutines and function
m odules
Passing parameters in subroutines and function
m odules
SAP AG
Chapter 10 Objectives
SAP AG
Overview of Modularization
PR OG RA M R SAAA 10A .
Call:
Calculate loss
Subroutine ..
.
Internal subroutine:
Calculate loss
SAP AG
If your program contains the same or similar statement sequences in several different places, you
can avoid this through modularization.
make your programs easy to read and improve their structure
A sequence of statements is defined in a module and can be called from various locations within
the program.
re-use program components
1. Both the subroutine and the call are in the same ABAP/4 program (internal call).
2. The subroutine itself is in an external program (external call).
3. Function modules are assigned to function groups and are stored centrally in the Function Library.
In
contrast to external subroutines, function modules have a clearly defined interface.
Calling and Defining Subroutines
REPORT RSAAA10A.
* Global data
TABLES: ... . X1 Y1
DATA: ... .
* Subroutines
FORM calculate_loss.
* statements
ENDFORM.
FORM write_loss.
* statements
ENDFORM.
SAP AG
To declare a subroutine, you use the key words FORM and ENDFORM. After FORM, you specify a
name (up to 30 characters).
For the sake of clarity, you should place all subroutines together at the end of the program.
To call subroutines, you use the PERFORM statement, followed by the name of the subroutine.
You can execute both nested and recursive subroutine calls.
Global and Local Data
REPORT
Dictionary tables
TABLES: ... .
(not program-specific)
DATA: ...
global data
X1 Y1
Subroutine call
X1 Y1
Subroutines
Parameters X Y
DATA: ... local data
statem ents
Parameters
DATA: ... local data X1
statements
SAP AG
Actual parameter
1 1 1 2 3
When a subroutine is called, the main program can pass data to the subroutine via an interface. Any
data determined in the subroutine is made available to the calling program.
The program and the subroutine can communicate via parameters. When defining a subroutine, you
specify formal parameters. When calling a subroutine, you specify actual parameters.
The assignment of actual and formal parameters depends on their position. Since each formal
parameter must be assigned to an actual parameter, there must be as many actual parameters as formal
parameters.
There are two types of parameters - input parameters and output parameters. You define input
parameters as call by value, and output parameters as call by reference or call by value and result.
Types of Parameter Passing
a1
call by value
f1
a1
a1
call by reference
f1
SAP AG
When specifying individual formal parameters, you use the VALUE addition. VALUE appears
immediately before the parameter name in parentheses. It defines a call by value for the relevant
formal parameters (e.g. FORM upro USING VALUE(f1) VALUE(f2) ...).
Call by reference
You specify the individual parameters after USING. This defines a call by reference for the
relevant formal parameters (e.g. FORM upro USING f1 f2 ...).
After CHANGING, you specify the parameters to be passed by value and result. When the subroutine
is called, these are assigned their own memory space. Also, the current contents of the formal
parameters are automatically passed to the assigned actual parameters at the end of the subroutine (at
ENDFORM).
If the CHECK <logical expression> statement in a subroutine returns a negative result or you leave
the subroutine with EXIT, the transfer is still performed because you leave the subroutine using
ENDFORM. Processing of the subroutine terminates immediately and ENDFORM is not performed
only if an error message (MESSAGE Ennn) is output or a STOP statement occurs.
Passing Parameters with Type Checking
PROGRAM RSAAA10C.
DATA: REVENUE ... .
.
.
.
PERFORM <nam e> USING
a1 a2 a3
a1 a2 a3 a4 a5.
. a4
.
. a5
FORM <nam e> USING 1 1
VALUE (f1) TYPE P 1
VALUE (f2) TYPE I 2
VALUE (f3) TYPE P
f4 LIKE REVENUE 3
f1
CHANGING VALUE (f5) TYPE P. f2
f3
<statements>
<statements>
f4
ENDFORM. f5
To ensure that a formal parameter of a subroutine is of a certain type, you can specify it in the FORM
statement. To do this, enter TYPE <t> or LIKE <f> after the formal parameter in the list after
TABLES, USING, or CHANGING.
When you call a subroutine with PERFORM, the system checks whether the types of the actual
parameters in the PERFORM statement are compatible with the types assigned to the formal
parameters. If the types are incompatible, the system outputs an error message during the syntax
check for the internal subroutine calls.
The following types of type checking are available when calling a subroutine:
No type, TYPE ANY The system accepts actual parameters of any type. All attributes of the
actual
parameter are passed to the formal parameter.
TYPE TABLE The system checks whether the actual parameter is an internal table. All
attributes and the structure of the table are passed from the actual
parameter to
the formal parameter.
TYPE C, N, P, or X The system checks whether the actual parameter is of type C, N, P, or X.
The
length of the parameter and its DECIMALS specification (for type P) are
passed from the actual parameter to the formal parameter.
TYPE D, F, I, or T, These types are fully determined. The system checks whether the LIKE
<f>, TYPE <ud> data type of the actual parameter precisely matches the
type
of the formal parameter (<ud> = user-defined).
Passing Structures as Parameters
REPORT RSAAA10D.
TABLES: SFLIGHT.
DATA: ... .
.
.
.
PERFORM write_sflight1 USING SFLIGHT.
PERFORM write_sflight2 USING SFLIGHT.
.
.
.
FORM write_sflight1 USING REC.
WRITE: / REC.
ENDFORM.
SAP AG
You can pass data structures (e.g. field strings, header lines of internal tables, table work areas) by
specifying LIKE or TYPE after the relevant formal parameter.
If you do not assign a type to the formal parameter, the single fields of the field string in the
subroutine cannot be addressed.
Passing Internal Tables as Parameters
REPORT RSAAA10E.
SAP AG
If you want to pass an internal table to a subroutine and access the individual fields of the table
entries, you must specify the type of the corresponding formal parameter (as with structures in FORM
statements).
You can pass internal tables with USING or TABLES. In contrast to TABLES, USING passes the
internal table together with the header line.
In the subroutine, you must define the TABLES parameter before USING. Internal tables are always
passed by reference. To assign a type to the table, use the STRUCTURE addition.
External Subroutines
Roll area
SFLIGHT
SPFLI
RSAAA10B
RSAAA10F
Occupied memory
SAP AG
Function Library
FM group: FIBU
Using function
FM _01 ...
Maintaining function modules
modules FM _02 ... PROGRAM ...
FM _02
FM group: ZIBU
TABLES ...
Interface
FM _03 ...
Import
FM _04 ...
Export CALL FUNCTION
Tables
'FM_02'
EXPORTING ...
Exceptions IMPORTING ...
Program
Docum entation
Administration
SAP AG
Function modules are classified in function groups and stored in the Function Library. A function
group contains functions which serve similar purposes (e.g. calendar functions) or functions with the
same data basis (1st function fills internal table, 2nd function edits internal table and so on).
You can assign a function group to a particular application (FI, HR) or flag it for general use (*).
Directory of Function Modules
Function group
Function name STRING*
STRING_LENGTH ---------------
SAP AG
You can use the Insert statement ... function in the ABAP/4 Editor to insert a statement into your
program in order to call a function module.
If you do not know the name of the function module, use the possible entries pushbutton to access the
Repository Information System and search generically in the Function Library using different citieria.
To create new function modules or to edit exiting ones, you use the Function Library function on the
initial screen of the ABAP/4 Development Workbench or the Object Browser.
Documenting and Calling Functions
REPORT RSAAA10G.
TABLES: SFLIGHT.
DATA: loss like sflight-paymentsum, revenue like ...
CALL FUNCTION 'CALCULATE_REVENUE_LOSS'
EXPORTING
PAYMENTSUM = SFLIGHT-PAYMENTSUM
SEATSOCC = SFLIGHT-SEATSOCC
PRICE = SFLIGHT-PRICE
IMPORTING
LOSS = LOSS
REVENUE = REVENUE.
SAP AG
Input and output parameters are defined for each function module. All elements of a function module
can be described by means of a short description and comprehensive documentation.
When a function module is called, the fields and field strings of the EXPORTING parameters are
passed to the function module. On return to the calling program, values are returned to the
IMPORTING parameters.
Parameters are assigned in the main program as follows:
formal parameter = actual parameter
The meaning of IMPORT and EXPORT depends on whether your viewpoint is the function module
or the calling program.
Describing the Interface
PAYMENTSUM ...
SEATSOCC ...
PRICE SFLIGHT-PRICE
REPORT RSAAA10G.
TABLES: SFLIGHT.
DATA: loss like sflight-paymentsum, revenue like ...
CALL FUNCTION 'CALCULATE_REVENUE_LOSS'
EXPORTING
PAYMENTSUM = SFLIGHT-PAYMENTSUM
SEATSOCC = SFLIGHT-SEATSOCC
PRICE = SFLIGHT-PRICE
IMPORTING
LOSS = LOSS
REVENUE = REVENUE.
SAP AG
Export parameters are passed by value (i.e. a copy of the field contents is passed) or by reference if
selected.
With export parameters, the specification of actual parameters is optional.
Import parameters are passed by value (i.e. a copy of the field contents is passed) or by reference if
selected.
Import parameters can contain default values. Default values can be literals, number constants,
system fields (SY-DATUM, SY-LANGU) or the pre-defined field SPACE. When passing parameters,
you can omit the actual parameter only if there is a default value or the import parameter is flagged as
optional. Import parameters with default values are always optional.
If you specify an ABAP/4 Dictionary reference field for a parameter, the system checks the type and
length of the actual parameter. If no reference field is specified, the system converts the actual
parameters according to the ABAP/4 conventions and does not perform any checks.
CHANGING Parameter
Changing param eter Ref. field Ref. type Proposal Optional Reference
f1 ...
REPORT ...
TABLES: SFLIGHT.
DATA: loss like sflight-paymentsum, revenue
like ...
CALL FUNCTION '...'
EXPORTING
...
IMPORTING
...
CHANGING
f1
... = a1
SAP AG
CHANGING parameters contain fields or field strings which are passed from the program to the
function module when the function module is called, and from the function module to the calling
program on return.
CHANGING parameters are passed by value (i.e. a copy of the field contents is passed) or by
reference if selected. CHANGING parameters must always contain values when they are called.
When passing the parameters, actual parameters can be omitted only if there is a default value or the
CHANING parameter is flagged as optional.
Passing Internal Tables
REPORT RSAAA10H.
TABLES: SFLIGHT.
DATA: ITAB like BCAXX OCCURS 10 WITH HEADER LINE.
CALL FUNCTION 'FILL_SEATTAB'
EXPORTING
YEAR = YEAR
TABLES
SEATTAB == ITAB.
ITAB
SAP AG
When internal tables are passed, they are not copied (call by reference).
You can assign internal tables to reference structures. These structures must be ABAP/4 Dictionary
objects. Type and length checks are performed for the actual parameters on the basis of this
assignment.
Like all parameters, tables can be flagged as optional.
Exception Handling
Exceptions
NO_ENTRY REPORT RSAAA10H.
CALL FUNCTION 'FILL_SEATTAB'
EXPORTING
YEAR = YEAR
TABLES
SEATTAB = ITAB
EXCEPTIONS
NO_ENTRY = 01
OTHERS = 02.
CASE SY-SUBRC.
WHEN 1.
WRITE 'No entry'.
WHEN 2.
WRITE 'Other error'.
ENDCASE.
SAP AG
When creating function modules, you can define exceptions. The calling program determines whether
and which exceptions it is to handle itself.
You can assign the same error number to several exceptions.
The OTHERS clause covers all exceptions not explicitly specified.
If an exception occurs during the execution of a function module, the exception either is handled in
the function module itself (e.g. by outputting an error message) or control immediately returns to the
calling program. The latter is only possible if the exception is specified in the EXCEPTIONS
parameter of the call.
You can address the general exception ERROR_MESSAGE for any function module: An error
message was displayed in the function module.
Creating Function Modules
Function Library
Create
SAP AG
A function module belongs to a function group. Each function group is assigned to a person who is
authorized to release function modules.
All function modules of a function group are managed in an ABAP/4 program.
Function module names can be up to 30 characters long and can consist only of alphanumeric
characters and the special underline character (_).
Function group names beginning with the letter Z and function module names beginning with the
characters Z_ are reserved for customers.
Interfaces
Z_FREESEAT
Global interface
Im port param eter Reference field Proposal
SEATSO CC SFLIGHT-SEATSOCC
SEATSM AX SFLIGHT-SEATSMAX
Export parameter
SEATSFREE SFLIGHT-SEATSMAX
Changing param eter
Exceptions
PLANE_OVERLOAD
Docum entation
Short text
Param eter Description F2
SEATSO CC
SAP AG
FUNCTION Z_FREESEAT.
* IMPORTING
* EXPORTING
* CHANGING
* TABLES
* EXCEPTIONS
local declarations
statem ents
ENDFUNCTIO N.
SAP AG
For each function module, the system generates a basic program structure. It inserts the defined
interfaces and exceptions as comment lines.
You can declare local data types.
You write the data declarations and statements relating to the function module in the FUNCTION ...
ENDFUNCTION block.
Exceptions
Z_FREESEAT
Exceptions
PLANE_O VERLO AD
call
.
.
.
CALL FUNCTION
EXPORTING ...
IMPORTING ...
EXCEPTIONS ...
program PLANE_OVERLOAD = 01.
. ... .
.
. CASE SY-SUBRC.
IF SEATSOCC > SEATSMAX. WHEN 1.
RAISE PLANE_OVERLOAD. .
.
* MESSAGE ... RAISING .
PLANE_OVERLOAD.
ENDIF. ENDCASE.
SAP AG
You define the names of exceptions in the interface of your function module. In the program, you
raise an exception with the following statements:
- RAISE <exception>.
or
- MESSAGE ... RAISING <exception>.
The effect of these statements depends on whether the calling program is to handle the raised
exception itself or not.
If the calling program is to handle the exception, control returns immediately to the calling program
without termination and without outputting any message. In this case, the EXPORT parameters are
always set to their initial values.
If the exception is not handled by the calling program. the function module terminates after the
RAISE statement. In the case of MESSAGE with the addition RAISING, the appropriate message is
output.
Test Environment
Test
SAP AG
When you have created a function module, you can test it in the test environment. You can specify
input values for the IMPORT parameters in an input template. The system transports the result to the
EXPORT parameters and then displays a list.
If an exception occurs, the raised exception is flagged.
The time required to execute the function module is displayed in microseconds. The same restrictions
apply to the calculated values here as in the Runtime analysis function. You should therefore repeat
the tests with the same data several times.
You can store test data in a test data directory.
You can test function modules with table parameters within the test environment.
You can create test sequences.
Subroutines
Main program
SAP AG
You can create a subroutine called only from a function module in the appropriate program module
(after ENDFUNCTION).
You create subroutines called from different function modules of the same function group in a
separate include program. To do this, enter the name of the include program in the main program of
the function group (use the Main program function).
Use L<group>Fxx as the name for the include program.
Global Data / Local Memory
Global Data
L<gr> TOP
FUNCTION-POOL <gr>.
DATA:X.
TABLES: ... .
Program Subroutine
L<gr> F01
FUNCTION ... .
DATA:... . FORM SUB1 USING ... .
MOVE X TO ... . DATA:... .
MOVE ... TO X.
ENDFUNCTION. ENDFORM.
SAP AG
You can use the Global data function to create fields and internal tables which you want to be
available as global data to all function modules and subroutines in a function group. Table work areas
(TABLES) are always global.
Any local fields of a function module which you declare in the function module program are
initialized each time the function module is called.
Global fields are initialized when a function module belonging to a particular function group is called
for the first time. When this function module or other function modules in the same group are called
again, the global data available contains the values from the last call. Using global data allows you to
implement a local memory for a function group.
Program Organization
L<gr>TOP
SAPL <gr>
FUNCTION-POOL<gr>
* System -defined include program s
MESSAGE-ID ZZ.
INCLUDE L<gr>TOP. DATA: "Global Data
INCLUDE L<gr>UXX
* User-defined include programs
L<gr>UXX
INCLUDE L<gr>U01.
INCLUDE L<gr>U02.
.
.
L<gr>U01 .
FUNCTION FA.
L<gr>U02
FUNCTION FB.
SAP AG
You create and maintain function modules with the Function Library function or in the Object
Browser. ABAP/4 manages the different programs and tables.
You access individual include programs only in exceptional cases (subroutines, dialog modules).
When creating a new function module, ABAP/4 creates another include program and determines the
name (number) of the program.
Administration of Function Modules
Adm inistration
.....
Person responsible LOTZ
Last changed by THIERM
Program SAPL<group>
Include L<group>UXX
Released on
Changed on 11.02.96
Active
SAP AG
To print function modules, choose the appropriate function in the Function module menu.
The person who last changed the function module makes the function module available using the
Activate function.
The person responsible for a function group releases a function module using the Administration
function.
Releasing a function module means that the module has been tested and the interface determined.
When a function module has been released, the interface cannot be changed. You cannot call function
modules until they have been activated, but you can call them before they have been released.
To change or expand the interface of a function module which has already been released, the person
responsible for the function group must cancel the release of that function module.
The Notes function allows the user of a function module to enter comments.
Summary of CALL FUNCTION
REPORT ... .
TABLES: ... .
DATA: ... .
CALL FUNCTION '...'
EXPORTING
f1 = a1
IMPORTING
f2 = a2
CHANGING
f3 = a3
TABLES
f4 = a4
EXCEPTIONS
not_found = 01.
CASE SY-SUBRC.
WHEN '01'.
...
ENDCASE.
SAP AG
When you call function modules with the CALL FUNCTION statement, you can use the following
parameters:
... EXPORTING p1 = f1 ... pn = fn: Passes fields, field strings and internal tables from the calling
program to the function module.
... IMPORTING p1 = f1 ... pn = fn: Returns fields, field strings and internal tables from the
function module to the calling program.
... CHANGING p1 = f1 ... pn = fn: Passes fields, field strings and internal tables to the function
module and returns the changed values.
... TABLES p1 = itab1 ... pn = itabn: Passes references to internal tables.
... EXCEPTIONS except1 = rc1 ... exceptn = rcn: Executes exceptions which the calling program
is to handle itself. When an exception occurs, SY-SUBRC is set to the assigned value rc and
control returns to the calling program.
With function modules, you can avoid the disadvantages of using conventional subroutines
because they have a precise interface and are managed in the Function Library.
Chapter 10 Summary
SAP AG
Exercises Chapter 10: Modularization
Task:
For each flight connection, calculate the sales for all flights of
an airline carrier.
Copy the report RSAAA107 to use as a model.
In this report, an internal table is defined with airline carrier,
flight connection, local currency and sales. When filling the
internal table, the report calculates the sales for the flight
connections.
Output the internal table in a subroutine by passing
parameters.
a) Example list
SOLU/CHAP 10.01: Sales of an airline carrier
----------------------------------------------------------------------------
Carrier Connection Sales Currency
LH 0400 168,950.00 USD
LH 0402 186,050.00 USD
LH 0454 196,000.00 USD
LH 0455 168,950.00 USD
LH 2402 168,950.00 USD
LH 2407 186,050.00 USD
LH 2415 196,000.00 USD
LH 2436 168,950.00 USD
LH 2462 168,950.00 USD
LH 2463 186,050.00 USD
LH 3577 196,000.00 USD
2. Name of your report: ZBCA##J2
##: Group number
Task:
Calculate the sales of all airline carriers.
The user should have to specifiy the airline carriers on the
selection screen.
Copy your report ZBCA##J1 or the example solution RSAAA101 to
use as a model. The internal field does not require a field for the
flight connection (SFLIGHT-CONNID).
The sales of the airline carriers (SFLIGHT-PAYMENTSUM) are posted
in the local currencies of the airline carriers (SFLIGHT-CURRENCY).
Calculate the sales in a single currency to be specified in a
PARAMETERS field. Use the standard function module
CONVERT_TO_LOCAL_CURRENCY.
a) Example list
SOLU/CHAP 10.02: Sales of all airline carriers
-----------------------------------------------------------------------------
Carrier Sales Currency
AA 405,617.92 USD
DL 243,301.29 USD
LH 1,990,900.00 DEM
UA 467,633.93 USD
Task:
Calculate the seat occupancy for all flights of an airline carrier
and output percentage values.
To do this, write a function module which calculates the seat
occupancy for a flight as a percentage.
c) Example list
SOLU/CHAP 10.03: Flight seat occupancy
-----------------------------------------------------------------------------------------
CARR CONN Flight date Max. capacity Occupied seats Percentage
TABLES: SFLIGHT.
END OF SALES.
COLLECT SALES.
ENDSELECT.
IF SY-SUBRC = 0.
ELSE.
MESSAGE S115.
ENDIF.
FORM WRITE_SALES USING ITAB LIKE SALES[ ].
(8) REC-CONNID,
REC-PAYMENTSUM,
REC-CURRENCY.
ENDLOOP.
ENDFORM.
REPORT RSAAA102 MESSAGE-ID AT.
* Calculate sales of carriers
TABLES: SFLIGHT.
END OF SALES,
COLLECT SALES.
EXPORTING
DATE = SY-DATUM
FOREIGN_AMOUNT = SALES-PAYMENTSUM
FOREIGN_CURRENCY = SALES-CURRENCY
LOCAL_CURRENCY = COM_CURR
IMPORTING
LOCAL_AMOUNT = LOC_AMOUNT
EXCEPTIONS
NO_RATE_FOUND = 1
OVERFLOW = 1
NO_FACTORS_FOUND = 1
OTHERS = 1.
IF SY-SUBRC = 1.
LOC_AMOUNT = 0.
WRITE: TEXT-002.
ELSE.
ENDIF.
ENDSELECT.
IF SY-SUBRC = 0.
ELSE.
MESSAGE S115.
ENDIF.
*-----------------------------------------------------------------
* Start of subroutines
*-----------------------------------------------------------------
REC-PAYMENTSUM,
REC-CURRENCY.
ENDLOOP.
ULINE.
* TEXT-001: Total
ENDFORM.
REPORT RSAAA103 MESSAGE-ID AT.
* Calculate occupancy of flights
TABLES: SFLIGHT.
*----------------------------------------------------------------*
*--------------------------------------------------------------- *
EXPORTING
SEATSOCC = SFLIGHT-SEATSOCC
SEATSMAX = SFLIGHT-SEATSMAX
IMPORTING
OCCUPANCY_PERCENTAGE = OCCUPANCY.
* EXCEPTIONS
* ZERO_DIVISION = 1
* OTHERS = 2.
WRITE: / SFLIGHT-CARRID,
SFLIGHT-CONNID,
SFLIGHT-FLDATE,
SFLIGHT-SEATSMAX,
SFLIGHT-SEATSOCC,
OCCUPANCY,
TEXT-001.
* text-001: %
ENDSELECT.
IF SY-SUBRC <> 0.
MESSAGE S115.
ENDIF.