1. Trang chủ
  2. » Công Nghệ Thông Tin

BC ABAP Programming PHẦN 4 pptx

153 391 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 153
Dung lượng 7,81 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Type specification Technical attributes of the formal parameter TYPE D, F, I, or T The formal parameter has the technical attributes of the predefined elementary typeTYPE The formal par

Trang 1

The Parameter Interface

screen, that is, in a PAI module, in the AT SELECTION-SCREEN event, or after an interactive listevent

Specifying the Type of Formal Parameters

Formal parameters can have any valid ABAP data type You can specify the type of a formalparameter, either generically or fully, using the TYPE or LIKE addition If you specify a generictype, the type of the formal parameter is either partially specified or not specified at all Anyattributes that are not specified are inherited from the corresponding actual parameter when thesubroutine is called If you specify the type fully, all of the technical attributes of the formalparameter are defined with the subroutine definition

The following remarks about specifying the types of parameters also apply to the parameters ofother procedures (function modules and methods)

If you have specified the type of the formal parameters, the system checks that the

corresponding actual parameters are compatible when the subroutine is called For internalsubroutines, the system checks this in the syntax check For external subroutines, the checkcannot occur until runtime

By specifying the type, you ensure that a subroutine always works with the correct data type.Generic formal parameters allow a large degree of freedom when you call subroutines, since youcan pass data of any type This restricts accordingly the options for processing data in the

subroutine, since the operations must be valid for all data types For example, assigning onedata object to another may not even be possible for all data types If you specify the types ofsubroutine parameters, you can perform a much wider range of operations, since only the dataappropriate to those operations can be passed in the call If you want to process structured dataobjects component by component in a subroutine, you must specify the type of the parameter

Specifying Generic Types

The following types allow you more freedom when using actual parameters The actual

parameter need only have the selection of attributes possessed by the formal parameter Theformal parameter adopts its remaining unnamed attributes from the actual parameter

Type specification Check for actual parameters

No type specification

TYPE ANY

The subroutine accepts actual parameters of any type Theformal parameter inherits all of the technical attributes of theactual parameter

TYPE C, N, P, or X The subroutine only accepts actual parameters with the type C,

N, P, or X The formal parameter inherits the field length andDECIMALS specification (for type P) from the actual parameter.TYPE TABLE The system checks whether the actual parameter is a standard

internal table This is a shortened form of TYPE STANDARDTABLE (see below)

TYPE ANY TABLE The system checks whether the actual parameter is an internal

table The formal parameter inherits all of the attributes (line type,table type, key) from the actual parameter

TYPE INDEX TABLE The system checks whether the actual parameter is an index

table (standard or sorted table) The formal parameter inherits all

of the attributes (line type, table type, key) from the actualparameter

TYPE STANDARD TABLE The system checks whether the actual parameter is a standard

internal table The formal parameter inherits all of the attributes(line type, key) from the actual parameter

Trang 2

The Parameter Interface

TYPE SORTED TABLE The system checks whether the actual parameter is a sorted

table The formal parameter inherits all of the attributes (line type,key) from the actual parameter

TYPE HASHED TABLE The system checks whether the actual parameter is a hashed

table The formal parameter inherits all of the attributes (line type,key) from the actual parameter

Note that formal parameters inherit the attributes of their corresponding actual parametersdynamically at runtime, and so they cannot be identified in the program code For example, youcannot address an inherited table key statically in a subroutine, but you probably can

dynamically

TYPES: BEGIN OF LINE,

COL1, COL2, END OF LINE.

DATA: WA TYPE LINE,

ITAB TYPE HASHED TABLE OF LINE WITH UNIQUE KEY COL1, KEY(4) VALUE 'COL1'.

WA-COL1 = 'X' INSERT WA INTO TABLE ITAB.

WA-COL1 = 'Y' INSERT WA INTO TABLE ITAB.

PERFORM DEMO USING ITAB.

FORM DEMO USING P TYPE ANY TABLE.

READ TABLE P WITH TABLE KEY COL1 = 'X' INTO WA.

is syntactically incorrect, since the formal parameter P does not adopt the key oftable ITAB until runtime

Specifying Full Types

When you use the following types, the technical attributes of the formal parameters are fullyspecified The technical attributes of the actual parameter must correspond to those of the formalparameter

Type specification Technical attributes of the formal parameter

TYPE D, F, I, or T The formal parameter has the technical attributes of the predefined

elementary typeTYPE <type> The formal parameter has the type <type> This is a data type defined

within the program using the TYPES statement, or a type from theABAP Dictionary

TYPE REF TO <cif> The formal parameter is a reference variable (ABAP Objects) for the

class or interface <cif>

TYPE LINE OF <itab> The formal parameter has the same type as a line of the internal table

<itab> defined using a TYPES statement or defined in the ABAPDictionary

LIKE <f> The formal parameter has the same type as an internal data object

<f> or structure, or a database table from the ABAP Dictionary

Trang 3

The Parameter Interface

When you use a formal parameter that is fully typed, you can address its attributes statically inthe program, since they are recognized in the source code

Structured Formal Parameters

Since formal parameters can take any valid ABAP data type, they can also take structures andinternal tables with a structured line type, as long as the type of the formal parameter is fully specified You can address the components of the structure statically in the subroutine

Generic Structures

If you pass a structured actual parameter generically to a formal parameter whose type is notcorrectly specified, you cannot address the components of the structure statically in the

subroutine For internal tables, this means that only line operations are possible

To access the components of a generically passed structure, you must use field symbols, andthe assignment

ASSIGN COMPONENT <idx>|<name> OF STRUCTURE <s> TO <FS> [Page 214]

<idx> is interpreted as the component number and the contents of <name> are interpreted as acomponent name in the generic structure <s>

DATA: BEGIN OF LINE,

COL1 VALUE 'X', COL2 VALUE 'Y', END OF LINE.

DATA COMP(4) VALUE 'COL1'.

PERFORM DEMO USING LINE.

FORM DEMO USING P TYPE ANY.

either statically or dynamically

Fitting Parameters into Structures

Instead of using TYPE or LIKE, you can specify the type of a structure as follows:

<pi> [STRUCTURE <s>]

where <s> is a local structure in the program (data object, not a type) or a flat structure from theABAP Dictionary The formal parameter is structured according to <s>, and you can address itsindividual components in the subroutine When the actual parameter is passed, the system onlychecks to ensure that the actual parameter is at least as long as the structure STRUCTUREtherefore allows you to force a structured view of any actual parameter

Trang 4

The Parameter Interface

DATA: BEGIN OF LINE,

COL1, COL2, END OF LINE.

DATA TEXT(2) VALUE 'XY'.

PERFORM DEMO USING TEXT.

FORM DEMO USING P STRUCTURE LINE.

WRITE: P-COL1, P-COL2.

ENDFORM.

The output is:

X Y

The string TEXT is fitted into the structure LINE

The TABLES Addition

To ensure compatibility with previous releases, the following addition is still allowed before theUSING and CHANGING additions:

FORM <subr> TABLES <itabi> [TYPE <t>|LIKE <f>]

The formal parameters <itabi> are defined as standard internal tables with header lines If youuse an internal table without header line as the corresponding actual parameter for a formalparameter of this type, the system creates a local header line in the subroutine for the formalparameter If you pass an internal table with a header line, the table body and the table workarea are passed to the subroutine Formal parameters defined using TABLES cannot be passed

by reference If you want to address the components of structured lines, you must specify thetype of the TABLES parameter accordingly

From Release 3.0, you should use USING or CHANGING instead of the TABLES addition forinternal tables, although for performance reasons, you should not pass them by value

Trang 5

Terminating Subroutines

Terminating Subroutines

A subroutine normally ends at the ENDFORM statement However, you can terminate themearlier by using the EXIT or CHECK statement When you terminate a subroutine with EXIT orCHECK, the current values of the output parameters (CHANGING parameters passed by value)are passed back to the corresponding actual parameter

Use EXIT to terminate a subroutine unconditionally The calling program regains control at thestatement following the PERFORM statement

PERFORM DIVIDE USING NUM1 NUM2 CHANGING RES

FORM DIVIDE USING N1 N2 CHANGING R

Trang 7

Naming Subroutines [Page 469]

Passing Parameters to Subroutines [Page 472]

Trang 8

Internal Subroutine Calls

To call a subroutine defined in the same program, you need only specify its name in the

External subroutine calls

The principal function of subroutines is for modularizing and structuring local

programs However, subroutines can also be called externally from other ABAPprograms In an extreme case, you might have an ABAP program that containednothing but subroutines These programs cannot run on their own, but are used byother ABAP programs as pools of external subroutines

However, if you want to make a function available throughout the system, you shoulduse function modules instead of external subroutines You create function modules inthe ABAP Workbench using the Function Builder They are stored in a central library,and have a defined release procedure

You can encapsulate functions and data in the attributes and methods of classes inABAP Objects For any requirements that exceed pure functions, you can use globalclasses instead of external subroutines

Trang 9

Naming Subroutines

When you call a subroutine externally, you must know the name of the program inwhich it is defined:

PERFORM <subr>(<prog>) [USING <pi> ]

[CHANGING <pi> ] [IF FOUND]

You specify the program name <prog> statically You can use the IF FOUND option toprevent a runtime error from occurring if the program <prog> does not contain asubroutine <sub> In this case, the system simply ignores the PERFORM statement.When you call an external subroutine, the system loads the whole of the programcontaining the subroutine into the internal session of the calling program (if it has notalready been loaded) For further information, refer to Memory Structure of an ABAPProgram [Page 66] In order to save memory space, you should keep the number ofsubroutines called in different programs to a minimum

Suppose a program contains the following subroutine:

PROGRAM FORMPOOL

FORM HEADER

WRITE: / 'Program started by', SY-UNAME,

/ 'on host', SY-HOST,

'date:', SY-DATUM, 'time:', SY-UZEIT

ULINE

ENDFORM

The subroutine can then be called from another program as follows:

PROGRAM FORM_TEST

PERFORM HEADER(FORMPOOL) IF FOUND

In this example, no data is passed between calling program and subroutine

Specifying Subroutines Dynamically

You can specify the name of a subroutine and, in the case of external calls, the name of theprogram in which it occurs, dynamically as follows:

PERFORM (<fsubr>)[IN PROGRAM (<fprog>)][USING <pi> ]

[CHANGING <pi> ]

[IF FOUND]

The names of the subroutine and the external program are the contents of the fields <fsubr> and

<fprog> respectively By using the option IF FOUND, you can prevent a runtime error from beingtriggered if <fprog> does not contain a subroutine with the name <fsubr> If you omit the

parentheses, this variant of the PERFORM statement behaves like the static variant

Suppose a program contains the following subroutines:

Trang 10

PERFORM (SUBRNAME) IN PROGRAM (PROGNAME) IF FOUND.

The produces the following output:

Subroutine 1

Subroutine 2

The character field PROGNAME contains the name of the program, in which thesubroutines are contained The names of the subroutines are assigned to the

character field SUBRNAME

Calling Subroutines from a List

You can call a subroutine from a list as follows:

PERFORM <idx> OF <subr1> <subr2> <subrn>

The system calls the subroutine specified in the subroutine list in position <idx> Youcan only use this variant of the PERFORM statement for internal subroutine calls, and

only for subroutines without a parameter interface The field <idx> can be avariable or a literal

In this example, the two internal subroutines, SUB1 and SUB2, are called

consecutively from a list

Trang 11

Passing Parameters to Subroutines

Passing Parameters to Subroutines

If a subroutine has a parameter interface [Page 461], you must supply values to all of the formalparameters in its interface when you call it You list the actual parameters after the USING orCHANGING addition in the PERFORM statement

When you pass the values, the sequence of the actual parameters in the PERFORM statement

is crucial The value of the first actual parameter in the list is passed to the first formal parameter,the second to the second, and so on The additions USING and CHANGING have exactly thesame meaning You only need to use one or the other However, for documentary reasons, it is agood idea to divide the parameters in the same way in which they occur in the interface

definition

Actual parameters can be any data objects or field symbols of the calling program whose

technical attributes are compatible with the type specified for the corresponding formal

parameter When you specify the actual parameters, note that any that you pass by reference to

a formal parameter, and any that you pass by value to an output parameter, can be changed bythe subroutine You should therefore ensure that only data objects that you want to be changedappear in the corresponding position of the actual parameter list

If a subroutine contains TABLES parameters in its interface, you must specify them in a TABLESaddition of the PERFORM statement before the USING and CHANGING parameters TABLESparameters are only supported to ensure compatibility with earlier releases, and should no longer

be used

You can specify actual parameters with variable offset and length specifications Offset

specifications for actual parameters function as offset specifications for field symbols You canselect memory areas that lie outside the boundaries of the specified actual parameter

PROGRAM FORM_TEST

DATA: A1 TYPE P DECIMALS 3,

A2 TYPE I, A3 TYPE D, A4 TYPE SPFLI-CARRID, A5 TYPE C.

CHANGING VALUE(F4) TYPE SPFLI-CARRID F5.

ENDFORM.

Trang 12

Passing Parameters to Subroutines

This example defines a subroutine SUBR with a parameter interface consisting of fiveformal parameter F1 to F5 The subroutine is called internally three times The actualparameters are the data objects A1 to A5 The three subroutine calls are all

equally valid. There are further PERFORM statements that are also equally valid, solong as the sequence of the actual parameters remains unchanged In each call, A1 ispassed to F1, A2 to F2, and so on When the subroutine ends, A3, A4, and A5 receivethe values of F3, F4, and F5 respectively The third of the subroutine calls documents

in the program what the parameter interface of the subroutine shows, namely that onlyA4 and A5 are changed Whether A3 is changed depends on the way in which thesubroutine is programmed

The following example shows how generically-typed formal parameters inherit their technicalattributes from their corresponding actual parameters

REPORT FORMTEST

DATA:

DATE1 TYPE D, DATE2 TYPE T,

STRING1(6) TYPE C, STRING2(8) TYPE C,

NUMBER1 TYPE P DECIMALS 2, NUMBER2 TYPE P,

COUNT1 TYPE I, COUNT2 TYPE I

PERFORM TYPETEST USING DATE1 STRING1 NUMBER1 COUNT1

SKIP

PERFORM TYPETEST USING DATE2 STRING2 NUMBER2 COUNT2

FORM TYPETEST USING NOW

TXT TYPE C

VALUE(NUM) TYPE P

INT TYPE I

DATA: T

DESCRIBE FIELD NOW TYPE T

WRITE: / 'Type of NOW is', T

DESCRIBE FIELD TXT LENGTH T

WRITE: / 'Length of TXT is', T

DESCRIBE FIELD NUM DECIMALS T

WRITE: / 'Decimals of NUM are', T

DESCRIBE FIELD INT TYPE T

WRITE: / 'Type of INT is', T

Trang 13

Passing Parameters to Subroutines

Trang 14

ADD_SUM = ADD_NUM1 + ADD_NUM2.

PERFORM OUT USING ADD_NUM1 ADD_NUM2 ADD_SUM

ADD_SUM, the latter parameters are then passed to the formal parameters

OUT_NUM1, OUT_NUM2, and OUT_SUM of the subroutine OUT

Input parameters which are changed in the subroutine are also changed in thecalling program To prevent this, you must pass the parameter by value in a

USING addition

Example of passing parameters by reference

PROGRAM FORM_TEST

Trang 15

Examples of Subroutines

DATA: NUM TYPE I VALUE 5,

FAC TYPE I VALUE 0

PERFORM FACT USING NUM CHANGING FAC

WRITE: / 'Factorial of', NUM, 'is', FAC

To ensure that an input parameter is not changed in the calling program, even if it

is changed in the subroutine, you can pass data to a subroutine by value In thisexample, the factorial of a number NUM is calculated The input parameter NUM

is passed to the formal parameter F_NUM of the subroutine Although F_NUM ischanged in the subroutine, the actual parameter NUM keeps its old value Theoutput parameter FAC is passed by reference

Example of output parameters

WRITE: / 'After subroutine:',

/ 'RES=' UNDER 'RES=', RES

Trang 16

To return a changed formal parameter once the subroutine has finished

successfully, you can use a CHANGING parameter and pass the parameter byreference In this example, the actual parameters OP1 and OP2 are passed byvalue in the USING addition to the formal parameters O1 and O2 The actual

parameter RES is passed by value to the formal parameter R using CHANGING

By writing R and RES onto the screen from within the subroutine, it is

demonstrated that RES has not changed its contents before the ENDFORM

statement After returning from the subroutine, its contents have changed

Example of passing structures

DATA WHO TYPE LINE

WHO-NAME = 'Karl' WHO-AGE = '10' WHO-COUNTRY = 'D'

PERFORM COMPONENTS CHANGING WHO

WRITE: / WHO-NAME, WHO-AGE, WHO-COUNTRY

FORM COMPONENTS

CHANGING VALUE(PERSON) TYPE LINE

WRITE: / PERSON-NAME, PERSON-AGE, PERSON-COUNTRY

typed with TYPE LINE Since LINE is a user-defined data type, the type of

PERSON is completely specified The subroutine accesses and changes the

components of PERSON They are then returned to the components of WHO inthe calling program

Trang 17

DATA ITAB LIKE STANDARD TABLE OF LINE.

PERFORM FILL CHANGING ITAB

PERFORM OUT USING ITAB

FORM FILL CHANGING F_ITAB LIKE ITAB

DATA F_LINE LIKE LINE OF F_ITAB

FORM OUT USING VALUE(F_ITAB) LIKE ITAB

DATA F_LINE LIKE LINE OF F_ITAB

LOOP AT F_ITAB INTO F_LINE

WRITE: / F_LINE-COL1, F_LINE-COL2

This example is provided for completeness The TABLES parameter is only

supported for the sake of compatibility and should not be used

PROGRAM FORM_TEST

Trang 18

DATA: ITAB TYPE STANDARD TABLE OF LINE WITH HEADER LINE,

JTAB TYPE STANDARD TABLE OF LINE

PERFORM FILL TABLES ITAB

MOVE ITAB[] TO JTAB

PERFORM OUT TABLES JTAB

FORM FILL TABLES F_ITAB LIKE ITAB[]

In this example, an internal table ITAB is declared with a header line and an

internal table JTAB is declared without a header line The actual parameter ITAB

is passed to the formal parameter F_ITAB of the subroutine FILL in the TABLESaddition The header line is passed with it After the body of the table has beencopied from ITAB to JTAB, the actual parameter is passed to the formal

parameter F_ITAB of the subroutine OUT using the TABLES addition The

header line F_ITAB, which is not passed, is generated automatically in the

subroutine

Trang 19

Shared Data Areas

Shared Data Areas

For the sake of completeness, this section describes a technique that allows you to access theglobal data of the calling program from an external subroutine To do this, you declare a

common data area for the calling program and the program containing the subroutine All

interface work areas [Page 131] declared using TABLES and NODES behave like the commondata area

Like external subroutines themselves, you should use common data areas very sparingly Therules [Page 498] for accessing common data areas can become very complicated if you callfunction modules from nested subroutines

You declare a common data area in all programs concerned using the statement:

DATA: BEGIN OF COMMON PART [<name>],

END OF COMMON PART [<name>]

Between the two DATA statements, you declare all of the data you want to include in the

common data area

The common part declaration must be exactly the same in all of the programs in which you want

to use it It is therefore a good idea to put the declaration in an include program

You can use several common parts in one program In this case, you must assign a name

<name> to each common part If you only have one common part in each program, you do nothave to specify a name To avoid conflicts between programs that have different common partdeclarations, you should always assign unique names to common parts

Assume an include program INCOMMON contains the declaration of a common partNUMBERS The common part comprises three numeric fields: NUM1, NUM2, andSUM:

END OF COMMON PART NUMBERS

The program FORMPOOL includes INCOMMON and contains the subroutinesADDIT and OUT:

Trang 20

Shared Data Areas

WRITE: / SFLIGHT-PLANETYPE, SFLIGHT-PRICE

SAPMZTST then produces the following output:

Trang 21

Shared Data Areas

All of the programs can access the table work area SFLIGHT, declared with theTABLES statement In the subroutine TABTEST2, the global work area is protectedagainst changes in the subroutine by the LOCAL statement

Trang 22

modules in the ABAP Workbench using the Function Builder [Extern].

Function modules allow you to encapsulate and reuse global functions in the R/3 System Theyare stored in a central library The R/3 System contains a wide range of predefined functionmodules that you can call from any ABAP program Function modules also play an importantrole in database updates [Page 1328] and in remote communications [Extern] between R/3Systems or between an R/3 System and a non-SAP system

Unlike subroutines, you do not define function modules in the source code of your program.Instead, you use the Function Builder [Extern] The actual ABAP interface definition remainshidden from the programmer You can define the input parameters of a function module asoptional You can also assign default values to them Function modules also support exceptionhandling This allows you to catch certain errors while the function module is running You cantest function modules without having to include them in a program using the Function Builder[Extern]

The Function Builder [Extern] also has a release process for function modules This ensures thatincompatible changes cannot be made to any function modules that have already been released.This applies particularly to the interface Programs that use a released function module will notcease to work if the function module is changed

Function Groups [Page 484]

Calling Function Modules [Page 486]

Creating Function Modules [Page 492]

Trang 23

Function Groups

Function Groups

Function groups are containers for function modules You cannot execute a function group.When you call an function module, the system loads the whole of its function group into theinternal session of the calling program (if it has not already been loaded) For further information,refer to Organization of External Procedure Calls [Page 498]

The following diagram shows the structure of a function group: The name of a function group can

be up to 26 characters long This is used by the system to create the components of the group(main program and corresponding include programs) When you create a function group orfunction module in the Function Builder [Extern] , the main program and include programs aregenerated automatically

Main program SAPL<fgrp>

ENDFUNCTION.

FUNCTION <name> .

ENDFUNCTION.

FUNCTION <name> .

ENDFUNCTION.

FUNCTION <name> .

ENDFUNCTION.

FUNCTION <name> .

ENDFUNCTION.

FUNCTION <name> .

• L<fgrp>UXX This contains further INCLUDE statements for the include programs

L<fgrp>U01, L<fgrp>U02, These includes contain the actual function modules

• The include programs L<fgrp>F01, L<fgrp>F02, can contain the coding of subroutinesthat can be called with internal subroutine calls from all function modules of the group.The creation of these include programs is supported from the ABAP Workbench by forwardnavigation (for example creation of a subroutine include by double clicking on the name of asubroutine in a PERFORM statement within a function module)

Trang 24

Function Groups

You cannot declare a COMMON PART in a function group Function groups have their own tablework areas (TABLES) Function groups encapsulate data In this respect, they are a precursor ofABAP Objects (see From Function Groups to Objects [Page 1349] )

All of the function modules in a function group can access the global data of the group For thisreason, you should place all function modules that use the same data in a single function group.For example, if you have a set of function modules that all use the same internal table, you couldplace them in a function group containing the table definition in its global data

Like executable programs (type 1) and module pools (type M), function groups can containscreens, selection screens, and lists User input is processed either in dialog modules or in thecorresponding event blocks in the main program of the function group There are special includeprograms in which you can write this code In this way, you can use function groups to

encapsulate single screens or screen sequences

Trang 25

Calling Function Modules

Calling Function Modules

This section describes calling function modules from the Function Builder

Finding Function Modules

Before programming a new function or creating a new function module, you should look in theFunction Builder to see whether there is an existing function module that already performs thesame task

For more information about this, refer to Finding Function Modules [Extern] in the ABAP

Workbench documentation For example, you might look for function modules that processstrings by entering *STRING*as a search criterion in the Repository Information System This is

an extract from the list of function modules found:

The title CSTR is the function group There is a main program SAPLCSTR that contains thesefunction modules If you select a function module, you can display its attributes in the FunctionBuilder

Important attributes:

• Documentation

The documentation describes the purpose of the function module, lists the parametersfor passing data to and from the module, and the exceptions It tells you how you canpass data to and from the function module, and which errors it handles

• Interface parameters and exceptions

This section provides further information about the interface parameters and exceptions,and how to use the function module For further information, refer to Displaying

Information about Interface Parameters [Extern] in the ABAP Workbench documentation.Function modules can have the following interface parameters:

• Import parameters These must be supplied with data when you call the function module,unless they are flagged as optional You cannot change them in the function module

• Export parameters These pass data from the function module back to the calling program.Export parameters are always optional You do not have to receive them in your program

• Changing parameters These must be supplied with data when you call the function module,unless they are flagged as optional They can be changed in the function module Thechanged values are then returned to the calling program

• Tables parameters You use these to pass internal tables They are treated like CHANGINGparameters However, you can also pass internal tables with other parameters if you specifythe parameter type appropriately

Trang 26

Calling Function Modules

You can specify the types of the interface parameters, either by referring to ABAP

Dictionary types or elementary ABAP types When you call a function module, you mustensure that the actual parameter and the interface parameters are compatible

Interface parameters are, by default, passed by value However, they can also be

passed by reference Tables parameters can only be passed by reference You canassign default values to optional importing and changing parameters If an optionalparameter is not passed in a function module call, it either has an initial value, or is set tothe default value

Exceptions are used to handle errors that occur in function modules The calling

program checks whether any errors have occurred and then takes action accordingly

Testing Function Modules

Before you include a function module in a program, you can test it in the Function Builder

Test in Function Builder

Import parameters

Export parameters

Exceptions Function module

For more information about this, refer to Testing Function Modules [Extern] in the ABAP

Workbench documentation

Calling Function Modules in ABAP

To call a function module, use the CALL FUNCTION statement:

CALL FUNCTION <module>

• After EXPORTING, you must supply all non-optional import parameters with values

appropriate to their type You can supply values to optional import parameters if you wish

• After IMPORTING, you can receive the export parameters from the function module byassigning them to variables of the appropriate type

Trang 27

Calling Function Modules

• After CHANGING or TABLES, you must supply values to all of the non-optional changing ortables parameters When the function module has finished running, the changed values arepassed back to the actual parameters You can supply values to optional changing or tablesparameters if you wish

You can use the EXCEPTIONS option to handle the exceptions of the function module If anexception <ei> is raised while the function module is running, the system terminates the functionmodule and does not pass any values from the function module to the program, except those thatwere passed by reference If <ei> is specified in the EXCEPTION option, the calling programhandles the exception by assigning <ri> to SY-SUBRC <ri> must be a numeric literal

If you specify of ERROR_MESSAGE in the exception list you can influence the message

handling of function modules Normally, you should only call messages in function modules usingthe MESSAGE RAISING statement With ERROR_MESSAGE you can force the system totreat messages that are called without the RAISING option in a function module as follows:

• Messages of classes S, I, and W are ignored (but written to the log in a background job)

• Messages of classes E and A stop the function module as if the exception

ERROR_MESSAGE had occurred (SY-SUBRC is set to <rE>)

If you specify OTHERS after EXCEPTIONS, the system assigns a single return code to all otherexceptions that you have not specified explicitly in the list

You can use the same number <ri> for several exceptions

The recommended and easiest way to call a function module is to use the Insert statement function in the ABAP Editor If you select Call Function and specify the

name of the function module (F4 help is available), the system inserts a CALLFUNCTION statements with all of the options of that function module in the

source code

Trang 28

Calling Function Modules

IF SY-SUBRC <> 0.

* MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO

* WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.

ENDIF.

STRING_SPLIT_AT_POSITION CALL FUNCTION

Insert Statement

Add values to actual parameters

Optional parts of the function call are inserted as comments In the above

example, STRING and POS are obligatory parameters LANGU, on the other

hand, is optional It has the default value SY-LANGU (the system field for the

logon language) Handling export parameters is optional Handling exceptions isalso theoretically optional However, you should always do so That is why theEXCEPTIONS lines are not commented out

You can trigger exceptions in the function module using either the RAISE or theMESSAGE RAISING statement If the calling program handles the exception,both statements return control to the program The MESSAGE RAISING

statement does not display a message in this case Instead, it sets the followingsystem fields:

• Message class → SY-MSGID

• Message type → SY-MSGTY

• Message number → SY-MSGNO

• SY-MSGV1 to SY-MSGV4 (contents of fields <f1> to <f4>, included in a message)

You can use the system fields to trigger the message from the calling program

To ensure that you use the right data types for the actual parameters, you mustrefer to the function module interface If you double-click the name of a function

Trang 29

Calling Function Modules

module in the source code of your program, the system navigates to its sourcecode in the Function Builder You can then display the interface by choosing

Goto → Interface.

For example, in the above case

• STRING, STRING1, and STRING2 have the generic type C The actual parameter mustalso have type C, but the length does not matter

• POS and POS_NEW have the fully-specified type I The actual parameter must also havetype I

• LANGU also has a fully-defined type, since it is defined with reference to the ABAP

Dictionary field SY-LANGU The actual parameter must have the same type

A complete call for the function module STRING_SPLIT_AT_POSITION mightlook like this:

PROGRAM CALL_FUNCTION.

DATA: TEXT(10) TYPE C VALUE '0123456789',

TEXT1(6) TYPE C, TEXT2(6) TYPE C.

PARAMETERS POSITION TYPE I.

CALL FUNCTION 'STRING_SPLIT_AT_POSITION'

STRING2_TOO_SMALL respectively For all other values of POSITION, the

exception POS_NOT_VALID is triggered

Trang 30

Calling Function Modules

Trang 31

Creating Function Modules

Creating Function Modules

You can only create function modules and function groups using the Function Builder in theABAP Workbench For further information, refer to Creating New Function Modules [Extern].This section uses an example to illustrate how a function module is created from the point of view

of ABAP programming

We are going to create a function module READ_SPFLI_INTO_TABLE to readdata for a specified airline from table SPFLI into an internal table, which it thenpasses back to the calling program

Function Groups and Function Modules

Firstly, we create a new function group DEMO_SPFLI to hold the function module(see Creating a Function Group [Extern]) Then, we can create the new functionmodule (see Creating a Function Module [Extern])

Parameter Interface

You can specify the types of interface parameters in function modules in the

same way as the parameter interfaces [Page 461] of subroutines Since functionmodules can be used anywhere in the system, their interfaces can only containreferences to data types that are declared systemwide These are the elementaryABAP data types, the systemwide generic types, such as ANY TABLE, and typesdefined in the ABAP Dictionary You cannot use LIKE to refer to data types

declared in the main program

The function module READ_SPFLI_INTO_TABLE requires an import parameter

to restrict the selection to a single airline To specify the type, we can refer to thekey field CARRID of the database SPFLI:

Change Function Module: READ_SPFLI_INTO_TABLE

Import Params

Under Ref field/structure, you can enter a column of a database table, a

component of a ABAP Dictionary structure, or a whole ABAP Dictionary structure.The import parameter ID is optional, and has a default value

The following type specification would have the same effect:

Trang 32

Creating Function Modules

Change Function Module: READ_SPFLI_INTO_TABLE

Import Params

Ref type can contain any generic or full data type that is recognized systemwide.Here, the parameter is defined with reference to the elementary ABAP Dictionarytype (or data element) S_CARR_ID This is the type used to define the field

SPFLI-CARRID

To pass data back to the calling program, the function module needs an exportparameter with the type of an internal table For this, we define a systemwidetable type SPFLI_TAB with the line type SPFLI in the ABAP Dictionary

Dictionary: Maintain Table Type SPFLI_TAB

Line typeType reference

Line type name SPFLI

Direct type specificationData type

We can now use this data type to specify the type of the export parameter ITAB:

Trang 33

Creating Function Modules

Change Function Module READ_SPFLI_INTO_TABLE

Export params

The internal table is passed by value Only internal tables that are passed usingtables parameters can be passed exclusively by reference

Exceptions

Our function module needs an exception that it can trigger if there are no entries

in table SPFLI that meet the selection criterion The exception NOT_FOUND

serves this function:

Fbaustein ändern: READ_SPFLI_INTO_TABLE

Exception

NOT_FOUND

Source Code

Having defined the parameter interface and exceptions, we can now write the

Function Builder This opens the ABAP Editor for the include program

L<fgrp>U<xx> (see Function Groups [Page 484] ) This is the include that will

hold the program code for the function module;

Trang 34

Creating Function Modules

Change F Module: READ_SPFLI_INTO_TABLE/LDEMO_SPFLI_U01

The source code of the function module occurs between the FUNCTION and

ENDFUNCTION statements The definitions of the parameter interface and theexceptions is displayed here in comment lines Its real coding is generated

invisibly by the Function Builder

Data in Function Modules

You can use the TYPES and DATA statements to create local data types and

objects The interface parameters also behave like local data objects In

addition, you can access all of the global data of the main program This data isdefined in the include program L<fgrp>TOP To open this include, choose Goto

Global data The global data behaves like the instance attributes of a class.The first time you call a function module in a particular function group, the data isloaded into memory It can then be accessed and changed by all of the functionmodules in the group The system retains the values until the next time a functionmodule is called

Calling Subroutines

also use this technique The function module that they call are defined in the

corresponding main program

If you only want to call a subroutine from a single function module, it is best todefine them in the same include program as the function module itself, directlyafter the ENDFUNCTION statement These subroutines can be called from allfunction modules in the function group, but for clarity, they should only be calledfrom the function module that precedes them

If you want to define a subroutine that will be called from several different functionmodules, you can define a special include program for it with the name

L<fgrp>F<xx>

Raising Exceptions

Trang 35

Creating Function Modules

There are two ABAP statements for raising exceptions They can only be used infunction modules:

RAISE <except>

and

MESSAGE RAISING <except>

The effect of these statements depends on whether the calling program handlesthe exception or not If the name <except> of the exception or OTHERS occurs

in the EXCEPTIONS addition of the CALL FUNCTION statement, the exception ishandled by the calling program

If the calling program does not handle the exception

processing continues depends on the message type

If the calling program handles the exception, both statements return control to theprogram No values are transferred The MESSAGE RAISING statementdoes not display a message Instead, it fills the system fields SY-MSGID, SY-

MSGTY, SY-MSGNO, and SY-MSGV1 to SY-MSGV4

Source Code of READ_SPFLI_INTO_TABLE

The entire source code of READ_SPFLI_INTO_TABLE looks like this:

FUNCTION READ_SPFLI_INTO_TABLE.

*" -SELECT * FROM SPFLI INTO TABLE ITAB WHERE CARRID = ID.

exception NOT_FOUND is triggered using MESSAGE RAISING Otherwise, thetable is passed to the caller as an exporting parameter

Calling READ_SPFLI_INTO_TABLE

The following program calls the function module READ_SPFLI_INTO_TABLE:

Trang 36

Creating Function Modules

REPORT DEMO_FUNCTION_MODULE.

PARAMETERS CARRIER TYPE S_CARR_ID.

DATA: JTAB TYPE SPFLI_TAB,

WA LIKE LINE OF JTAB.

CALL FUNCTION 'READ_SPFLI_INTO_TABLE'

LOOP AT JTAB INTO WA.

WRITE: / WA-CARRID, WA-CONNID, WA-CITYFROM, WA-CITYTO.

Trang 37

Organization of External Procedure Calls

Organization of External Procedure Calls

opened in the current R/3 terminal session When the program calls external procedures, theirmain program and working data are also loaded into the memory area of the internal session.Here, there is a difference between calling external subroutines, function modules, and workingwith classes in ABAP Objects

Program Groups in an Internal Session

This illustration shows the memory organization for external subroutines and function modules

If you call an external subroutine using PERFORM, the main program of the subroutine is loadedinto the existing main program or function group in the corresponding main or additional programgroup (if it has not already been loaded)

An additional program group is only opened in an external PERFORM if the subroutine belongs

to a function group that has not yet been loaded This will happen if the main program of thesubroutine begins with the FUNCTION-POOL statement The program type does not necessarilyhave to be set to F

Classes in ABAP Objects behave like function groups The first time you address a class (forexample, using the CREATE OBJECT statement) or address a static class component, thesystem opens an additional program group for the class

Trang 38

Organization of External Procedure Calls

Screen Handling

The system only displays and processes the screens, selection screens, and lists of the mainprogram and main program group or function group of an additional program group, along withtheir associated GUI statuses The CALL SCREEN and CALL SELECTION-SCREEN

statements or list display statements in external subroutines apply to the screens of the mainprogram or function group The screens are processed in the main program or function group

So, for example, even if the main program of an external subroutine has a screen 100, the CALL

Interface Work Areas

Interface work areas [Page 131] that you declare using the TABLES, NODES, or DATA BEGIN

OF COMMON PART statements exist once only in each program group, and are shared by all ofits programs Each main program that begins with the PROGRAM or REPORT statement, andeach function group that begins with FUNCTION-POOL shares the interface work areas with themain programs of all of its external subroutines

Dynamic Assignment

of the subroutine calls The first program to call an external subroutine shares its interface workareas with the subroutine, and the subroutine uses its screens The sequence of the subroutinecalls is not necessarily statically defined Instead, it can change dynamically depending on useractions or the contents of fields For example, a subroutine may belong to a main program group

on occasion when it is run, but the next time, it may belong to an additional program group Forthis reason, you should avoid using external subroutines if they use interface work areas or callscreens

Trang 39

Special Techniques

Special Techniques

Berechtigungen überprüfen [Page 506]

Laufzeitmessung von Programmsegmenten [Page 512]

Programme dynamisch generieren und starten [Page 517]

Trang 40

Catchable Runtime Errors

Catchable Runtime Errors

Runtime errors occur when the ABAP runtime environment discovers an error at runtime thatcould not be detected while the program was being created A runtime error may be catchable ornon-catchable This section contains an overview of the different ABAP program checks and adescription of how to handle catchable runtime errors

Program Checks [Page 502]

Catching Runtime Errors [Page 504]

Ngày đăng: 09/08/2014, 14:20

TỪ KHÓA LIÊN QUAN