Program Layout

«« Previous
Next »»

Program Layout, Oracle Java Tutorials and Materials, Oracle Java Guides, Oracle Java Certifications
  • Each ABAP program starts with an introductory statement that depends on the program type.
  • The functions of an ABAP program are implemented in processing blocks. Processing blocks are defined using modularization statements. Declarative statements in processing blocks of the type procedure can be used to define local data types and data objects. The other processing blocks do not have a local data area, and any declarative statements apply to the program globally. The most important processing blocks in ABAP objects are methods. They can only implement their class in the implementation part. The order of the processing blocks or implementation parts is irrelevant for program execution, but should be designed to make the program easy to read.
  • Every ABAP program provides predefined data types, data object and predefined functions.
  • Following the introductory statement, every program contains a global declaration part, in the definitions and declarations are implemented that are valid and visible in the entire program. This includes the declaration of data types and data objects, as well as the definition of interfaces or the declaration part of classes in ABAP Objects. The definitions of interfaces and classes contain the declarations of their components. While the order of the individual definitions and declarations is not specified, it must be noted that an ABAP statement can only refer to existing definitions and declarations. For example, a reference variable can only refer to a previously defined class, which in turn can only implement a previously defined interface. Once a procedure has been introduced, data types and data objects that are visible within the procedure can be declared. The declaration of data types also includes the typing of objects that have an undetermined data type when the program is created.
  • All the other statements of an ABAP program are implementation statements, which can always be assigned to a processing block. The implementation statements are used to implement the functions of a processing block. The functions of all processing blocks are largely implemented using the same statements.
  • Since ABAP is a language that has grown over time, it contains several obsolete additions of statements that have been replaced with improved language constructs, but which have not been eliminated to ensure downward compatibility. In ABAP Objects - that is, in the implementation of methods -, almost all of the obsolete language elements will fail syntax checks. In general, these language elements should no longer be used in new programs, but they may still be encountered in older programs.

1. ABAP Program Types

The type of an ABAP program determines (among other things) which declarations and processing blocks a program can contain and how the program can be executed in the ABAP runtime environment.

The following table shows all program types for standalone programs (compilation units) and how the attributes of the programs are affected by the type.

Program Type Execution Global Declarations  Processing Blocks  Dynpros  Text Pools
Executable program Statement SUBMIT or a dynpro or selection screen is called using a transaction code Local interfaces and classes, all other declarative statements All (except function modules) Yes  Yes 
Class pool Call of a visible method or a call using a transaction code A global class from the class library, local interfaces and classes, statements TYPES and CONSTANTS Methods only No Yes 
Function group or function pool A function module is called using CALL FUNCTION or a dynpro is called using a transaction code Local interfaces and classes, all other declarative statements All (except event blocks for reporting events) Yes  Yes 
Interface pool None A global interface from the class library None  No  No 
Module pool A dynpro is called using a transaction code Local interfaces and classes, all declarative statements All (except function modules and event blocks for reporting events) Yes  Yes 
Subroutine pool External call of local procedures (subroutines or methods) Local interfaces and classes, all other declarative statements Event block LOAD-OF-PROGRAM, subroutines, methods No  Yes 
Type group or type pool None Statements TYPES and CONSTANTS None No  No

The second column of the table shows which category of execution the program type is designed for. The third column shows which declarations can be made in the global declaration section of a program with the specified type. The fourth column shows which processing blocks the program can contain. The fifth indicates whether the program can support its own dynpros. The final column indicates whether the program can create its own text pools.

2. Introductory Statements for Programs

The introductory statements for programs are:

◉ REPORT
◉ PROGRAM
◉ FUNCTION-POOL
◉ CLASS-POOL
◉ INTERFACE-POOL
◉ TYPE-POOL.

The introductory statement of each program depends on the program type specified in the program attributes.

All statements that follow the introductory statements in the source code or are included as include programs are handled as a single unit by ABAP Compiler.

The first statement of every independent ABAP program must be an introductory statement, and each program can only contain one of these statements. The only other statement allowed in the first position (alongside the introductory statement) is the INCLUDE statement. In this case, an introductory statement for a program must appear in the first position of the program after the include program has been resolved when the program is generated.

Executable programs, module pools, function groups, class pools, interface pools, subroutine pools, and type groups are standalone compilation units. Include programs, on the other hand, are only used in the context of compilation units.

Type groups, also known as type pools, are standalone programs from a logical point of view. However, they do not contain executable code but only type definitions and constant definitions. For this reason, type groups have their own introductory program statement, the TYPE-POOL.

Note: It is not mandatory, from a syntax point of view, to assign introductory program statements to the program types defined in the program attributes. However, the assignments described in the following sections should always be used. When a program is created, the suitable statement is created automatically by ABAP Workbench and should be changed only in the additions, when editing. In particular, the keywords FUNCTION-POOL, CLASS-POOL, INTERFACE-POOL, and TYPE-POOL should be created solely by the respective tools of ABAP Workbench and never be entered in the source code themselves, to avoid unexpected system behavior.

1. REPORT


Syntax

REPORT rep [list_options]
           [MESSAGE-ID mid]
           [DEFINING DATABASE ldb]
           [REDUCED FUNCTIONALITY].

Additions

1. ... MESSAGE-ID mid

2. ... REDUCED FUNCTIONALITY

Effect

The statement REPORT introduces an executable program. It must be the first statement of a standalone program after the triggering of possible include programs. The name rep must be specified directly. The optional additions list_options can be used to modify the basic list of the program. A message class can be specified using MESSAGE-ID.

The addition DEFINING DATABASE is used to define a logical database, whereas REDUCED FUNCTIONALITY shoudl only be used for PROGRAM.

Notes

1. In the above statement, the keyword REPORT can be replaced by the keyword PROGRAM. In executable programs, PROGRAM means the same as REPORT and can be used with the additions of REPORT. As a rule, only initiate executable programs using REPORT.

2. Although it is not absolutely necessary to specify the name rep, the name of the ABAP program from the repository should always be used.

Addition 1

... MESSAGE-ID mid

Effect

This addition specifies a message class mid that, in the program, allows the use of short forms of the statement MESSAGE in which only the message type and message number are specified. The message class must be specified directly and appear in the column ARBGB of the database table T100. The variations of statement MESSAGE, in which the message class is specified, override the addition MESSAGE-ID.

Example

Default setting of the message class Z_MY_MESSAGES for the program Z_MY_REPORT.

REPORT z_my_report MESSAGE-ID z_my_messages.

Addition 2

... REDUCED FUNCTIONALITY

Effect

This addition is only intended for the statement PROGRAM in subroutine pools and is described there.

1.1 REPORT - list_options

Syntax

... [NO STANDARD PAGE HEADING]
    [LINE-SIZE width]
    [LINE-COUNT page_lines[(footer_lines)]] ...

Additions

1. ... NO STANDARD PAGE HEADING

2. ... LINE-SIZE width

3. ... LINE-COUNT page_lines[(footer_lines)]

Effect

These additions influence the basic list of the program.

Addition 1

... NO STANDARD PAGE HEADING

Effect

This addition suppresses the output of the standard page header (standard header and column headers) on the basic list of the program and sets the system field sy-wtitl to the value "N". This setting can be overwritten when the list is created using the additions NO-TITLE|WITH-TITLE and NO-HEADING|WITH-HEADING of the statement NEW-PAGE.

Addition 2

... LINE-SIZE width

Effect

This addition specifies the line width of the basic list and details list of the program to width characters, and sets the system field sy-linsz to this value. The line width determines the number of characters in the line buffer as well as the number of columns in the list displayed. The value width must be specified directly as a positive number. The maximum line width is 1023.

When the LINE-SIZE is not specified, the line width of the basic list is set to a standard width based on the window width of the current dynpro, but is at least as wide as a standard size GUI window. For the standard width, the contents of sy-linsz is 0. The LINE-SIZE overwrites the value of the addition LINE-SIZE of the statement SUBMIT and can be overwritten when the list is created using the addition LINE-SIZE of the statement NEW-PAGE.

Note: The current maximum line width is stored in the constants SLIST_MAX_LINESIZE of the type group SLIST. Also defined there is a type SLIST_MAX_LISTLINE of type c with length SLIST_MAX_LINESIZE. The constant SLIST_MAX_LINESIZE cannot be used in the statement REPORT but can be used in the statement NEW-PAGE.

Addition 3

... LINE-COUNT page_lines[(footer_lines)]

Effect

This addition specifies the page length for the basic list of the program to page_lines lines and fills the system field sy-linct with this value. If LINE-COUNT is not specified and for page_lines less than 0 or greater than 60000, the page length is set internally to 60000. This setting overwrites the value passed by the (similarly named) addition LINE-SIZE of the statement SUBMIT and can be overwritten when the list is created by the (similarly named) addition LINE-COUNT of the statement NEW-PAGE.

If a number is specified for footer_lines, a corresponding number of lines are reserved for the page footer, which can be described in the event block END-OF-PAGE.

page_lines and footer_lines must be specified directly as positive numbers, where no sign can be specified for footer_lines.

Notes

1. The default value should be used for screen lists since, as a rule, page breaks specified using LINE-COUNT are not adjusted to the window size.

2. The default value should also be used for spool lists, so that the page size can be selected on a printer-specific basis. A spool list should be created in such a way that it provides satisfactory results for any page size.

3. Specifying a fixed line count is only useful for form-like lists with a fixed page layout. Here, however, always check whether these forms can be created by other means.

Example

Sets the page length of the basic list to 65 lines, eight of which are reserved for the page footer. The line width is 132 characters.

REPORT z_myreport LINE-COUNT 65(8) LINE-SIZE 132.

2. PROGRAM


Syntax

PROGRAM prog [list_options]
             [MESSAGE-ID mid]
             [REDUCED FUNCTIONALITY].

Addition:

... REDUCED FUNCTIONALITY

Effect

The statement PROGRAM initiates a module pool or a subroutine pool. It must be the first statement of a standalone program after the triggering of possible include programs. The name prog must be specified directly. The following applies for the additions:

◉ In module pools, the additions list_options and MESSAGE-ID of the statement PROGRAM have the same meaning as the additions of the same name in the statement REPORT. The addition REDUCED FUNCTIONALITY works only in subroutine pools and is otherwise ignored.
◉ In subroutine pools, the specification of MESSAGE-ID has the same meaning as with the statement REPORT.. The possible additions list_options for the basic list are ignored, since subroutine pools do not have a separate list buffer. Output statements in subroutine pools write to the current list of the calling main program. The addition REDUCED FUNCTIONALITY only works in subroutine pools..

Notes

◉ In the above statement, the keyword PROGRAM can be replaced by the keyword REPORT. In module pools or subroutine pools, REPORT has the same meaning as PROGRAM and can be used with its additions. As a rule, module pools and subroutine pools should only be introduced by using PROGRAM.
◉ The name prog is not absolutely necessary, but the name of the ABAP program from the repository should always be used.
◉ The name of a module pool is not fixed, but should follow the naming conventions in ABAP Workbench. These specify that the name of module pools should start with "SAPM".

Addition

... REDUCED FUNCTIONALITY

Effect

This addition only has an effect in programs of program type subroutines pool. In other program types, the syntax check raises a warning. In a subroutine pool initiated with the addition REDUCED FUNCTIONALITY, not all components that are usually loaded with an ABAP program are loaded. This reduces the program load and memory consumption in the roll area. This means that the full ABAP language range is not available.

◉ The embedded structure syst is not loaded. Instead of syst, the structure sy with the same meaning can be used.

◉ The embedded structure screen is not loaded. The statements LOOP AT SCREEN and MODIFY SCREEN are then not possible.

◉ Editing is not possible with the dynpros of the main program of the current program group .

◉ No support is available for spooling lists. The corresponding additions of the statements NEW-PAGE and SUBMIT cannot be changed.

If none of the missing functions are required, the addition REDUCED FUNCTIONALITY can be used to avoid the unnecessary resources being consumed by subroutine pools.

Notes

◉ The addition REDUCED FUNCTIONALITY also works in subroutine pools which were created with GENERATE SUBROUTINE POOL.

◉ The use of REDUCED FUNCTIONALITY is especially recommended for small subroutine pools which only contain simple help procedures

◉ The use of REDUCED FUNCTIONALITY in a subroutine pool produces warning from the syntax check, pointing out that the entire ABAP range is not available. If nonexistent functions are used, corresponding syntax errors are produced.

3. FUNCTION-POOL


Syntax

FUNCTION-POOL fpool [list_options]
                    [MESSAGE-ID mid].

Effect

The statement FUNCTION-POOL introduces a function group. It must be the first statement of a standalone program after the triggering of possible include programs. The additions of the statement FUNCTION-POOL have the same function as the additions of the statement REPORT.

Function groups are defined using the Function Builder tool in ABAP Workbench; a master program and subordinate include programs are generated automatically. The statement FUNCTION-POOL is created in the top include.

The full name of the master program of a function group in the repository consists of the prefix SAPL and the name fpool of the statement FUNCTION-POOL.

A function group is used as a container for function modules and is organized in include programs as follows.

◉ One top include with the prefix "L" and the ending "TOP" in the declaration part of the function group.

◉ Optional include programs with the prefix "L" and the ending "D.." for declaring local classes within the top include.

◉ One include program with the prefix "L" and the ending "UXX" in the implementation part of the function group. This include program includes include programs with the ending "U.." for implementing each function module of the function group. This structure must not be changed.

◉ Optional include programs with the prefix "L" and the ending "P.." for implementing the methods of local classes in the implementation part of the function group.

◉ Optional include programs with the prefix "L" and the ending "O.." for implementing PBO modules in the implementation part of the function group.

◉ Optional include programs with the prefix "L" and the ending "I.." for implementing PAI modules in the implementation part of the function group.

◉ Optional include programs with the prefix "L" and the ending "E.." for implementing event blocks in the implementation part of the function group.

◉ Optional include programs with the prefix "L" and the ending "F.." for implementing subroutines in the implementation part of the function group.

The periods ".." represent a two-digit number. The functions in Function Builder are based on adherence to this naming convention.

Example

Function group SAPLABAP_DOCU is structured from include programs.

*&---------------------------------------------------------------------*
*&  Function Group SAPLABAP_DOCU
*&---------------------------------------------------------------------*

INCLUDE labap_docutop.               " Global Declarations

INCLUDE labap_docue00.               " Load of Program

INCLUDE labap_docuuxx.               " Function Modules

INCLUDE labap_docuo01.               " PBO Modules

INCLUDE labap_docui01.               " PAI Modules

INCLUDE labap_docue01.               " Handling of Runtime-Events

INCLUDE labap_docup01.               " Class implementations
INCLUDE labap_docup02.
INCLUDE labap_docup03.
INCLUDE labap_docup04.
The function group includes the top include in the first place; it contains the statement FUNCTION-POOL and other include programs for data and class declarations:

*&---------------------------------------------------------------------*
*&  Include           LABAP_DOCUTOP
*&---------------------------------------------------------------------*

FUNCTION-POOL abap_docu.

INCLUDE labap_docud00.               " Global Data for Screens

INCLUDE labap_docud01.               " Classes for Docu Display

4. CLASS-POOL


Syntax

CLASS-POOL [MESSAGE-ID id].

Effect

The statement CLASS-POOL introduces a class pool. It must be the first statement of a standalone program, after any include programs have been called. The addition MESSAGE-ID of the statement CLASS-POOL has the same meaning as for the REPORT statement.

Class pools are edited in Class Builder in ABAP Workbench. A master program for a global class, and associated include programs, are generated automatically. The statement CLASS-POOL is created in the master program.

The full name of the master program of a class pool in the repository starts with the name of the global class, is padded with the character "=" up to and including position 30, and ends with "CP".

The names of the include programs of a class pool included by the master program are constructed in exactly the same way as the name of the class pool itself, however they have different endings. Unlike the case with function groups, the actual structure of a class pool constructed from include programs is the internal responsibility of ABAP Workbench and the ABAP runtime environment and is not displayed in Class Builder.

Note: The statements permitted in a class pool are listed under Statements in Class Pools and Interface Pools.

Example

The name of the master program of the class pool of the global class CL_ABAP_BROWSER is CL_ABAP_BROWSER===============CP.

5. INTERFACE-POOL


Syntax

INTERFACE-POOL.

Effect

The statement INTERFACE-POOL introduces an interface pool. It must be the first statement of an independent program after resolving possible include programs.

Interface pools are edited only with the tool Class Builder in ABAP Workbench. A master program for a global interface including the statement INTERFACE-POOL is generated automatically.

The full name of the master program of an interface pool in the repository starts with the name of the global interface, is padded with the character "=" up to and including position 30, and ends with "IP".

The names of the include programs of an interface pool included by the master program are constructed in exactly the same way as the name of the interface pool itself, however they have different endings. Unlike the case with function groups, the actual structure of an interface pool constructed from include programs is the internal responsibility of ABAP Workbench and the ABAP runtime environment and is not displayed in Class Builder.

Note: The statements permitted in an interface pool are listed under Statements in Class Pools and Interface Pools.

Example

The name of the master program of the interface pool of the global interface IF_DEMO_CR_CAR_RENTL_SERVICE is IF_DEMO_CR_CAR_RENTL_SERVICE==IP.

6. TYPE-POOL


Syntax

TYPE-POOL tpool.

Effect

The statement TYPE-POOL introduces a type group called tpool. It must be the first statement of a type group after any include programs are resolved. Type groups are only defined in ABAP Dictionary in ABAP Workbench. Here, an ABAP program is generated automatically, including the statement TYPE-POOL. The actual name of the program of a type group in the repository does not completely match the name of the type group and is of internal relevance only.

Type groups can only contain the following statements:

◉ INCLUDE
◉ INCLUDE TYPE|STRUCTURE
◉ TYPES
◉ CONSTANTS
◉ DEFINE and END-OF-DEFINITION
◉ CLASS ... DEFINITION DEFERRED PUBLIC

Here, the declared data types, constants, and macros must be prefixed with the name tpool of the type group. The elements declared in a type group can be addressed statically or dynamically by name in every ABAP program in which the type group can be used. The type group is loaded when an element of a type group is first accessed.

Notes

◉ Types in type groups are the predecessors for general type definitions in ABAP Dictionary.
◉ Since it is possible to also define data types and constants in the public visibility section of global classes, type groups are obsolete and should no longer be created. Existing type groups can still be used.
◉ To avoid conflicts in the type reference with the addition LIKE, it must be ensured that constants in type groups do not have the same name as existing flat structures or database tables in ABAP Dictionary.
◉ The name of a type group may contain a maximum of five characters.
◉ Previously, type groups had to be made known in ABAP programs using the statement TYPE-POOLS before their elements could be accessed statically or dynamically. This restriction is now obsolete. The statement TYPE-POOLS is no longer necessary.

Example

Type group with the definition of a table type.

TYPE-POOL mytgr.
TYPES mytgr_spfli_tab TYPE HASHED TABLE
                      OF spfli
                      WITH UNIQUE KEY carrid connid.

3. Modularization Statements


Each ABAP program is divided into processing blocks. Each accessible statement of an ABAP program that does not belong to the global declaration part of the program belongs to a processing block.

The possible processing blocks are:

1. Procedures 
ABAP statements are used to process procedures. Possible procedures are: methods , function modules, and subroutines
2. Dialog modules 
Dialog modules are called from dynpro flow logic.
3. Event blocks 
The processing of event blocks is triggered by events in the ABAP runtime environment.

Processing blocks can be defined in any order in the source code of an ABAP program. Non-declarative statements that appear between or after closed processing blocks cannot be accessed and can never be executed. The syntax check reports dead source code of this nature as errors. Declarative statements that appear between or after closed processing blocks are part of the global data declarations of an ABAP program and are visible in all subsequent processing blocks.

Macros and include programs can be used to modularize source code while avoiding processing blocks.

1. Procedures

Procedures are processing blocks with an interface and a local data area. They can be called from within ABAP programs. The possible types of procedure are:

◆ Methods
◆ Function modules

An obsolete type of procedure are:

◆ Subroutines

1.1 Parameter Interface of Procedures

The parameter interface of a procedure consists of formal parameters and specifies the exceptions possible in the procedure.

Formal Parameters

Formal parameters are input parameters, output parameters, input/output parameters, or return values. Several obsolete table parameters also exist. Formal parameters are either generic or fully typed. Pass by reference or pass by value can be specified for most formal parameters. Pass by value is mandatory for some formal parameters.

Exceptions

Class-based exceptions can be declared using RAISING for all procedures (methods, function modules, and subroutines), and can then be propagated from the procedure. EXCEPTIONS can also be used in methods and function modules to define non-class-based exceptions, which can then be raised in the procedure using RAISE or MESSAGE ... RAISING.

Pass by Reference or Pass by Value

When deciding whether to use pass by reference or pass by value for a formal parameter, the performance and robustness of each pass-by type must be compared.

In ABAP, pass by reference always leads to better performance since no local data object has to be stored and no data transport is necessary when the procedure is called. Therefore, for performance reasons, pass by reference is usually preferable, unless explicit or implicit writes are made to an input parameter in the procedure or if it is necessary to ensure that an input/output parameter or an output parameter is returned only if the procedure ends without any errors. In such cases, pass by value is mandatory, to make sure that the assigned actual parameter is not simultaneously modified in the caller when writes are made on a formal parameter. For performance reasons, only parameters of 100 bytes or less should be passed in these cases, whenever possible.

Also note the following when using pass by reference:

◉ In subroutines, writes can be made to an input parameter defined using USING without a syntax error being produced (as is the case with input parameters of methods or function modules defined using IMPORTING).
◉ An output parameter that is passed by reference acts like an input/ output parameter; in other words, if reads are performed to an output parameter in the procedure before the value of that parameter is changed, this value is not initial (unlike in pass by value), but is the same as the current value of the actual parameter in the caller.
◉ If a procedure is stopped because of an error (that is, if it is stopped for a reason other than reaching its last statement or RETURN, EXIT, or CHECK) all actual parameters that are passed by reference retain the value of the assigned formal parameter that that parameter had when the program was stopped. In pass by value, no values are passed to actual parameters when a procedure terminates.

Procedures and their calls have to be programmed so that these kinds of errors do not occur.

To summarize, pass by reference is always preferable when performance is an issue, while pass by value is more suitable in situations where robustness and data consistency are more important. These factors must be taken into account in each individual case when deciding which pass-by type to use with which type of parameter.

Notes

◉ When strings or internal tables of the same type are passed by value, table sharing comes into force between the data object created locally and the data object passed, as in assignments. However, table sharing only happens if the row type of the internal table permits it. This means that, when passing strings and internal tables, the performance benefits of pass by reference over pass by value may be negated by sharing (in certain circumstances).
◉ Only pass by reference can be specified for the obsolete table parameters.
Pass by value is mandatory for the return value of functional methods, the output parameters of events in ABAP Objects, and all formal parameters of RFC-enabled function modules and update function modules (pass by value is also used implicitly with table parameters).
◉ A local data object is created for formal parameters passed by reference that are not bound to an actual parameter during the call (as for pass by value).
◉ There are special rules for defining literals and functions and expressions as actual parameters.
◉ The result of the typing check when passing actual parameters to formal parameters is independent of the pass type. In a pass by value, the check for pass by reference is always carried out, even though this is stricter than necessary in individual cases. For example, a special reference variable cannot be passed to a general typed CHANGING parameter, even if pass by value is defined for this parameter.

1.1.1 Passing Parameters

The example demonstrates the difference between passing a parameter in a procedure by value or by reference.

Source Code

REPORT  demo_procedure_param.

CLASS demo DEFINITION.
  PUBLIC SECTION.
    TYPES: BEGIN OF line,
               x TYPE i,
               y TYPE i,
               range TYPE i,
           END OF line.

    CLASS-DATA: param TYPE STANDARD TABLE OF line,
                res TYPE i.
    CLASS-METHODS: main,
                   fill_table  CHANGING  g_param LIKE param,
                   solve_table IMPORTING g_param LIKE param,
                   fibb IMPORTING VALUE(l_line) TYPE line
                        EXPORTING VALUE(r) TYPE i.
ENDCLASS.

CLASS demo IMPLEMENTATION.
  METHOD main.
    fill_table(  CHANGING  g_param = param ).
    solve_table( EXPORTING g_param = param ).
  ENDMETHOD.

  METHOD fill_table.
    g_param = VALUE #( FOR j = 1 UNTIL j > 3
                       ( x = j
                         y = j ** 2
                         range = 12 / j ) ).
  ENDMETHOD.

  METHOD solve_table.
    DATA l_line LIKE LINE OF g_param.
    LOOP AT g_param INTO l_line.
      fibb( EXPORTING l_line = l_line IMPORTING r = res ).
      cl_demo_output=>write(
      |Fibb( { l_line-x }, { l_line-y }, { l_line-range }) = { res }| ).
    ENDLOOP.
    cl_demo_output=>display( ).
  ENDMETHOD.

  METHOD fibb.
    IF l_line-range = 1.
      IF l_line-x < l_line-y.
        r = l_line-x.
      ELSE.
        r = l_line-y.
      ENDIF.
    ELSEIF l_line-range = 2.
      IF l_line-x < l_line-y.
        r = l_line-y.
      ELSE.
        r = l_line-x.
      ENDIF.
    ELSE.
      l_line-range = l_line-range - 2.
      DO l_line-range TIMES.
        IF l_line-x < l_line-y.
          l_line-x = l_line-x + l_line-y.
          r = l_line-x.
        ELSE.
          l_line-y = l_line-x + l_line-y.
          r = l_line-y.
        ENDIF.
      ENDDO.
    ENDIF.
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  demo=>main( ).

Description

Method fibb calculates the sequence term with number range of a Fibonacci sequence using the start values x and y. As a rule, the next sequence term is always the total of two previous sequence terms (therefore two start values). The method takes the parameters, a structured parameter l_line used to pass the input values, and a parameter r of type i used to output the result. Since the parameter l_line is defined as an IMPORTING parameter but still has to be changed in the method, the method definition must contain the keyword value before the parameter; otherwise a syntax error occurs. This ensures that within the method a local copy of the parameter is used. The addition value to the output parameter r has the effect that the result is assigned to the static class attribute res only after the method has been processed completely. Otherwise res would be changed in each single step of the algorithm.

The internal table param contains the input values for calculating three different sequence terms of the Fibonacci sequence. Method fill_table is used to fill param with values, and method solve_table is used to calculate and output fibb for each line of param.

1.2 Methods

Methods are the procedures of a class whose functions are implemented between the statements

METHOD
  ...
ENDMETHOD

The statement METHOD does not usually have any additions. Exceptions to this rule are:

◈ Methods used to implement ABAP Managed Database Procedures (AMDP)
◈ Kernel-Methoden zur internen Verwendung

1.2.1 METHOD

Syntax

METHOD meth.
  ...
ENDMETHOD.

Effect

Between the statements METHOD and ENDMETHOD, the function of a method meth declared using [CLASS-]METHODS is implemented in a class. The implementation of a method is only possible in an implementation part of a class that begins with CLASS class IMPLEMENTATION

Local data types and data objects can be declared within the method. It is also possible to access the formal parameters of the method and all the components of all instances of its own class. The method and its interface are defined either using the statement [CLASS-]METHODS for a local class, or in the Class Builder tool for a global class.

In instance methods, all components of the class of the method and the instance of the method can also be addressed explicitly using the self reference me->, as well as using their names. In addition, all components of other instances from the class of the method can be addressed using reference variables.

A method can be called statically or dynamically. For static calls, both standalone and functional call forms are available. Dynamic calls are always standalone calls.

Note

◉ When a method of an interface intf is implemented, meth can be specified either as the name declared in the interface (prefixed with intf~) or as an alias name of the class defined using ALIASES. The method must exist in the interface; otherwise a syntax error is produced. If intf~ is used, only a syntax warning will appear for global interfaces, so that classes are not immediately rendered invalid if an unused method is deleted from a global interface.

◉ The addition BY DATABASE PROCEDURE transforms a method implemented in a database-specific language (and not in ABAP) and executed in the database system to an AMDP method.

Example

In this example, the two methods m1 and m2 of the class c1 between METHOD and ENDMETHOD are implemented. Although the local data object a1 hides the attribute of the same name, the attribute a1 can be addressed using me->a1.

CLASS c1 DEFINITION.
  PUBLIC SECTION.
    METHODS m1 IMPORTING p1 TYPE string.
  PRIVATE SECTION.
    DATA a1 TYPE string.
    METHODS m2.
ENDCLASS.
CLASS c1 IMPLEMENTATION.
  METHOD m1.
    a1 = p1.
    m2( ).
  ENDMETHOD.
  METHOD m2.
    DATA a1 TYPE string.
    a1 = me->a1.
  ENDMETHOD.
ENDCLASS.

◉ METHOD - Internal Additions

Internal Additions

These additions are for internal use only. 
Do not use them in application programs. 

Addition:

... BY KERNEL MODULE p1 ... 

Effect

This addition of the statement METHOD defines the method meth as a kernel method. This means that the method meth is not implemented in ABAP but in the kernel instead by using one of the kernel modules p1 specified here. No statements are allowed between METHOD and ENDMETHOD.

Note

In global classes, the addition must be entered directly in the source code editor in Class Builder and is not specified under the properties of the method there.

1.2.2 ENDMETHOD

Syntax

ENDMETHOD.

Effect

The statement ENDMETHOD closes a method implementation introduced using METHOD.

1.3 Function Modules

Function modules are cross-program, reusable procedures that are organized into function groups, and whose functions are implemented between the statements FUNCTION and ENDFUNCTION. Function modules and their interfaces are created in the Function Builder.


Syntax

FUNCTION func.
*"---------------------------------------------------------
*" Local Interface:
*" parameter_interface
*"---------------------------------------------------------
  ...
ENDFUNCTION.

Effect

Between the statements FUNCTION and ENDFUNCTION, the functions of a function module func are implemented in a function group. The function module and its interface are defined in the Function Builder tool. In the source code of the function module, the function module interface defined in Function Builder is automatically displayed as parameter_interface in comment lines underneath the statement FUNCTION.

Within the function module, local data types and data objects can be declared. There is also access to the formal parameters of the function module and to the global data types and data objects of the function group. A function module is called using the statement CALL FUNCTION.

Note

The predicate expression IS SUPPLIED can be used in the function module to determine whether an actual parameter has been specified for a formal parameter.

Example

Implements a function module that reads data in a table-like formal parameter flight_tab under the condition of an elementary formal parameter id. The parameter interface defined in Function Builder is visible as a comment.

FUNCTION read_spfli_into_table.
*"---------------------------------------------------------
*" Local Interface:
*"       IMPORTING
*"             VALUE(ID) LIKE  SPFLI-CARRID DEFAULT 'LH '
*"       EXPORTING
*"             FLIGHT_TAB TYPE  SPFLI_TAB
*"---------------------------------------------------------
  SELECT *
         FROM spfli
         WHERE carrid = @id
         INTO TABLE @flight_tab.
ENDFUNCTION.

◉ Function Module Interface

The parameter interface of a function module is defined in Function Builder. It includes the definition of interface parameters and the specification of exceptions that can be raised by a function module. Function Builder creates comment lines below the statement FUNCTION automatically in the source code of the function module. These represent the interface of the function module with the following syntax:

Syntax

... [IMPORTING parameters]
    [EXPORTING parameters]
    [TABLES table_parameters]
    [CHANGING parameters]
    [{RAISING exc1|RESUMABLE(exc1) exc2|RESUMABLE(exc2) ...}
    |{EXCEPTIONS exc1 exc2 ...}]

The syntax and semantics of IMPORTING, EXPORTING, CHANGING, RAISING, and EXCEPTIONS mainly correspond to the definition of method interfaces with [CLASS-]METHODS. The additional option of defining table parameters using TABLES is obsolete.

Note

The ABAP Development Tools do not have a form-based Function Builder and the parameter interface of a function module is defined in an ABAP pseudo syntax. These statements are not compiled like genuine ABAP statements and the regular ABAP syntax checks are not applied. When a function module is generated, they are interpreted like the form-based instructions from classic Function Builder.

Interface Parameters

The interface parameters are defined on the relevant tab pages in Function Builder.

IMPORTING parameters are input parameters. When the function module is called, a suitable actual parameter must be specified for every non-optional input parameter. The content of the actual parameter is passed to the input parameter when the call is made. The content of an input parameter for which 'pass by reference' is defined cannot be changed in the function module.
EXPORTING parameters are output parameters. When the function module is called, a suitable actual parameter can be specified for every output parameter. The content of an output parameter that is defined for 'pass by value' is passed to the actual parameter if the function module is completed without errors. An output parameter that is defined for pass by reference is not initialized when the function module is called.
◆ TABLES parameters are obsolete table parameters.
CHANGING parameters are input and output parameters. When the function module is called, a suitable actual parameter must be specified for every non-optional input or output parameter. When the function module is called, the content of the actual parameter is passed to the input/output parameter, and when the function module is completed, the content of the input/output parameter is passed to the actual parameter.

Note: The formal parameters of a function module can be registered as global parameters in Function Builder, however this is obsolete.

Exceptions

The exceptions of a function module are defined on the Exceptions tab page in Function Builder. Here exception classes can be selected to define whether class-based exceptions are declared or non-class-based exception are defined. Class-based exceptions are represented in the above syntax by RAISING, and non-class-based exceptions are represented by EXCEPTIONS.

◆ The addition RAISING is used to declare class-based exceptions that can be propagated from the function module to the caller. Exceptions in the categories CX_STATIC_CHECK and CX_DYNAMIC_CHECK must be explicitly declared, to prevent propagations from violating the interface. A violation of the interface raises the handleable exception CX_SY_NO_HANDLER. Exceptions of the category CX_NO_CHECK are always declared implicitly and with addition RESUMABLE. The declaration of exceptions of the category CX_STATIC_CHECK is checked statically in the syntax check. For exceptions of the category CX_DYNAMIC_CHECK, the check is not performed until runtime. In a function module in which class-based exceptions are declared using the addition RAISING, the statement CATCH SYSTEM-EXCEPTIONS cannot be used. Instead, the relevant handleable exceptions should be handled in a TRY control structure.

The addition RESUMABLE declares an exception that can be propagated as a resumable exception. This addition has no relevance to a non-resumable exception. The addition does not have any effect on a non-resumable exception. If a resumable exception is propagated with RAISING without the addition RESUMABLE, it thus becomes non-resumable. If a superclass is declared as resumable, any subclasses must also be declared as resumable.

◆ The addition EXCEPTIONS is used to define a list of non-class-based exceptions that can be raised in the function module using the statements RAISE or MESSAGE RAISING. Exceptions defined in this way are (as with formal parameters) bound to the function module and cannot be propagated. If an exception of this type is raised in a function module, and no return value has been assigned to it with the identically named addition EXCEPTIONS of the statement CALL FUNCTION when the call was made, a runtime error is produced. In a function module in whose interface non-class-based exceptions are defined, the statement RAISE EXCEPTION or the addition THROW in a conditional expression cannot be used to raise class-based exceptions.

The Resumable column in Function Builder can be selected to flag a class-based exception as a resumable exception. This places the addition RESUMABLE behind RAISING in the syntax above.

◉ Properties of Interface Parameters

When an interface parameter p1, p2... is defined in Function Builder, properties are determined for the parameter which are reflected in the syntax of parameters and table_parameters.

Syntax

... { VALUE(p1) | REFERENCE(p1) }
         [ {TYPE [REF TO] type} | like_structure
           [OPTIONAL|{DEFAULT def1}] ]
    { VALUE(p2) | REFERENCE(p2) }
         [ {TYPE [REF TO] type} | like_structure
           [OPTIONAL|{DEFAULT def2}] ]
    ...

The syntax and semantics of VALUE, TYPE, OPTIONAL, and DEFAULT are mainly the same as in the definition of method interfaces by [CLASS-]METHODS. The obsolete option like_structure also exists, which uses LIKE or STRUCTURE to type interface parameters.

Type of Parameter Passing

There are two types of parameter passing: pass by reference and pass by value. Pass by value is selected in Function Builder by selecting pass by value and differs from pass by reference in the above syntax (indicated by REFERENCE( )) by VALUE( ) being specified. If only one name p1 p2 ... is specified, the parameter is passed by reference by default.

◈ In pass by reference, the formal parameter points directly to the actual parameter, so that changes to the formal parameters have an immediate effect on the actual parameter.
◈ In pass by value, when the function module is called, the formal parameter is created as a copy of the actual parameter (in IMPORTING and CHANGING parameters), or initial (in EXPORTING parameters) in the stack. In CHANGING and EXPORTING parameters, the formal parameter is copied to the actual parameter when returning from the function module.

Note the following for the different types of parameter:

◈ In IMPORTING, EXPORTING, and CHANGING parameters, pass by reference and pass by value are possible, in TABLES parameters, only pass by reference is possible.
◈ IMPORTING parameters passed by reference must not be overwritten in the function module.
◈ An EXPORTING parameter passed by reference behaves like a CHANGING parameter, which means that EXPORTING parameters passed by reference are not initialized when the function module is called. For this reason, no reads should be performed on these parameters before the first write. In addition, be careful when adding content to such parameters as, for example, when inserting rows into internal tables.

Note: The time the function module was last edited specifies whether a parameter passed by reference is displayed with or without REFERENCE( ). REFERENCE( ) is displayed for function modules modified in Release 7.31 and later.

Typing of Interface Parameters

The parameter interface of a function module is public across the system. Interface parameters can therefore only be typed with reference to data types from ABAP Dictionary or from the public visible section of global classes. In Function Builder, interface parameters can be typed selecting either TYPE or TYPE REF TO or by entering LIKE.

Typing with TYPE [REF TO] is the recommended typing for interface parameters of function modules. It takes place when TYPE or TYPE REF TO is selected in Function Builder. For IMPORTING, EXPORTING, and CHANGING parameters, any predefined ABAP type (complete or generic), or any data type from ABAP Dictionary or from the public visibility section of a global class can be specified after TYPE. After TYPE REF TO, the generic data type data, a non-generic data type, or an object type can be specified and the interface parameter is typed as a reference variable. The typing check is performed in the same way as for methods.

Note: Without an explicit typing, a formal parameter is typed implicitly with the fully generic type any.

Optional Parameters

IMPORTING, CHANGING, and TABLES parameters can be made optional by the selection of optional in Function Builder. EXPORTING parameters are always optional. IMPORTING and CHANGING parameters can be assigned a replacement parameter (default value in Function Builder). In the above syntax, this is expressed using the additions OPTIONAL or DEFAULT. For an optional parameter, no actual parameter must be entered when the function module is called. While a formal parameter with the addition OPTIONAL is then initialized as a type-friendly parameter, a formal parameter with the addition DEFAULT assumes the value and type of the replacement parameter def1 def2 ....

If no actual parameter is specified for a generically typed formal parameter with the addition OPTIONAL when it is called, the type of the formal parameter is completed according to fixed rules.

Note

Within a function module, the predicate expression IS SUPPLIED can be used to check whether an optional formal parameter was assigned an actual parameter when it was called.

1.3.2 ENDFUNCTION

Syntax

ENDFUNCTION.

Effect

The statement ENDFUNCTION closes a function module introduced using FUNCTION.

2. Dialog Modules

Dialog modules help prepare and process screens of the dynpro. You cannot declare local data types and data objects within a dialog module, whose functionality is implemented between the statements MODULE and ENDMODULE. All declarative statements in dialog modules belong to the global data declaration of the ABAP program and are visible in all following processing blocks. A dialog module works with the global data types and data objects of the framework program and therefore should not contain its own declarations.

2.1 MODULE

Syntax

MODULE mod {OUTPUT|[INPUT]}.
  ...
ENDMODULE.

Addition:

... OUTPUT|[INPUT]

Effect

The statement MODULE defines a dialog module mod. The naming conventions apply to the name mod. The functions of a dialog module mod are implemented between the statements MODULE ad ENDMODULE.

A dialog module is called using the identically named statement MODULE of the dynpro flow logic of any dynpro of an ABAP program .

Addition

... OUTPUT|[INPUT]

Effect

The additions OUTPUT and INPUT determine whether the dialog module can be called for the PBO event or for the PAI event. The addition INPUT is the default and can therefore also be omitted, although this is not recommended for the readability of the program. Two dialog modules with the same name can be defined in a program, if one of them has the addition OUTPUT and the other has the addition INPUT, which is also not recommended for reasons of readability.

Note

For data encapsulation reasons, it is recommended that very few functions are implemented in dialog modules and that procedures are called instead.

2.2 ENDMODULE

Syntax

ENDMODULE.

Effect

The statement ENDMODULE closes a module definition introduced using MODULE.

3. Event Blocks

Event blocks are used to handle events in the ABAP runtime environment. They are introduced by an event key word and finished by the next processing block. Since there is no closing statement, we recommend that you flag the end of an event block with a comment line.

Within an event block, no local data types or data objects can be declared. All declarative statements in event blocks belong to the ABAP program, and are visible in all subsequent processing blocks. An event block works with the global data types and data objects of the framework program, and therefore should not contain any of its own declarations. Exception: The event blocks AT SELECTION-SCREEN ... and GET ... are implemented internally as procedures and can contain local data).

For reasons of data encapsulation, it is advisable to only implement a few functions in event blocks, and to call methods instead.

The following events exist:

◉ Program constructor event
This event occurs in all program types, except for class pools and interface pools.
◉ Reporting Events
These events only occur in executable programs.
◉ Selection screen and list events occur during selection screen processing or list processing.

Notes

◉ When the execution of each event block is completed, the statement NEW-LINE is executed.
◉ With the exception of AT SELECTION-SCREEN ... and GET ... event blocks can be listed multiple times in a program. Event block START-OF-SELECTION can also be implicitly listed multiple times. Whenever an event occurs, all associated event blocks are executed in the order of their occurrence. Where event blocks are implicitly listed multiple times, the extended program check posts a warning.

3.1 Program Constructor

The program constructor can be used to initialize the global data of a program. It is introduced using the statement

LOAD-OF-PROGRAM

The associated event occurs when a program is loaded into the internal session.

Note

Class pools do not have a program constructor, since the static constructor from the global class defined in the class pool can be used instead.

3.1.1 LOAD-OF-PROGRAM

Syntax

LOAD-OF-PROGRAM.

Effect

This event keyword defines the program constructor of an executable program, a module pool, a function group, or a subroutine pool. The program constructor is an event block whose event is raised by the ABAP-runtime environment when one of the executable programs mentioned above is loaded into the internal session.

When a program is called using SUBMIT or using a transaction code, a new internal session is opened in every call and the event block is executed once in every call. Global data objects of the program can be initialized here. The event block must be fully executed, otherwise a runtime error occurs. This means that statements can be specified that exit the event block without returning to it.

The first time an external procedure (subroutine or function module) or a subscreen is called, the master program of the called procedure is loaded into the internal session of the caller, thus raising the event LOAD-OF-PROGRAM. The event block is executed before the called procedure. Each time a procedure of the same master program is called again by a caller of the same internal session, the event LOAD-OF-PROGRAM is not raised.

Notes

◉ The event LOAD-OF-PROGRAM should mainly be used to initialize global data when calling external procedures or transactions. If executable programs are called using SUBMIT, it is recommended that the event INITIALIZATION is used, since the start values for parameter and selection criteria are set after LOAD-OF-PROGRAM (see program flow after SUBMIT).

◉ If a program is only loaded because declarations are required from it, such as when using absolute type names, the LOAD-OF-PROGRAM event is not raised. The program constructor is only executed if an executable unit of the program is called afterwards.

◉ Class pools do not have a program constructor, since the static constructor from the global class defined in the class pool can be used instead.

3.2 Reporting Events

Event key words for reporting events include:

◉ INITIALIZATION,
◉ START-OF-SELECTION,
◉ GET node (obsolete, for logical databases only),
◉ END-OF-SELECTION (obsolete, for logical databases only).

Reporting events occur in a predefined sequence and only in executable programs started using SUBMIT. In general, every executable program is implicitly started using SUBMIT. Only when a regular transaction code (not a reporting transaction) is used for the start (or external calls of their procedures), is a SUBMIT not triggered.

When an executable program is associated with a logical database, the assigned subroutine is executed in the database program before a reporting event is triggered.

3.2.1 INITIALIZATION

Syntax

INITIALIZATION.

Effect

This event keyword defines an event block for initializing an executable program. The associated event is raised by the ABAP runtime environment during the flow of an executable program, directly after LOAD-OF-PROGRAM and before the selection screen processing of any existing standard selection screen. This enables the input fields of the selection screen to be initialized once-only, including those fields defined in the logical database associated with the program.

Note

When an executable program defines a standard selection screen, it is called again by the ABAP runtime environment after execution, which raises the event INITIALIZATION again. In this case, the initialization of parameters or selection criteria of the selection screen is ignored, because they are automatically supplied with the preceding user input from the selection screen during the selection screen event AT SELECTION-SCREEN OUTPUT. To explicitly initialize the selection screen for each call, the event AT SELECTION-SCREEN OUTPUT must be used.

3.2.2 START-OF-SELECTION

Syntax

START-OF-SELECTION. 

Effect

This event keyword defines the standard processing block of an executable program. The associated event is raised by the ABAP runtime environment during the running of an executable program after any standard selection screens have been processed.

In an executable program, all statements that are not declarations and that are specified before the first explicit processing block, or if the program does not contain any explicit processing blocks, all functional statements of the program are assigned to an implicit event block START-OF-SELECTION, which is inserted before any explicit START-OF-SELECTION event blocks.

Note

If the program is associated with a logical database, preparatory tasks can be performed in START-OF-SELECTION before the logical database imports the data. If the program is not associated with a logical database, this event block becomes a type of "main program" from which procedures or classic screens are called.

Example

The following are three executable programs with exactly the same functions:

The first program contains an explicit event block START-OF-SELECTION and shows the recommended spelling.

REPORT test_start_of_selection. 

DATA text TYPE string. 

START-OF-SELECTION. 
  text = `Hello World!`. 
  cl_demo_output=>display_data( text ).

In the second program, an assignment is inserted before the first processing block, which forms a second implicit event block START-OF-SELECTION before the explicit event block.

REPORT test_start_of_selection. 

DATA text TYPE string. 

text = `Hello World!`. 

START-OF-SELECTION. 
  cl_demo_output=>display_data( text ).

In the third program, there is no explicit processing block. All statements implicitly form the event block START-OF-SELECTION.

REPORT test_start_of_selection. 

DATA text TYPE string. 

text = `Hello World!`. 
cl_demo_output=>display_data( text ).

The third program has exactly the same meaning as the first program. The second program, in contrast, would have the following form if expressed explicitly:

REPORT test_start_of_selection. 

DATA text TYPE string. 

START-OF-SELECTION. 
  text = `Hello World!`. 

START-OF-SELECTION. 
  cl_demo_output=>display_data( text ).

3.3 Selection Screen and List Events

Selection screen and list events are events from classical screen processing, which are converted by the ABAP runtime environment into ABAP events and are handled directly in the ABAP program instead of in the dynpro flow logic.

◉ Selection screen eventsoccur during selection screen processing.
◉ List events occur during classical list processing.

They are described in their respective environment.

4. Source Code Modules

Source code modularization is the segmentation of a program's source code into individual units. Modularization operates independently of the segmentation of an ABAP program into processing blocks.

Source code modules are implemented as either include programs or as macros. Include programs are used to structure large programs, whereas macros are used to recycle individual parts of programs.

4.1 Include Programs

Include programs are used to split ABAP source code into individual repository objects. An ABAP program can be created in the program attributes using the program type include program. Include programs do not need to contain introductory statements for programs and cannot be generated independently from the ABAP compiler. When using the statement INCLUDE, however, include programs can be integrated into compilation units.

An include program must contain complete statements. It can include other include programs but not it cannot include itself. An include program does not need to contain complete processing blocks.

Notes

◉ For the global declaration section of an ABAP program, a special top include is available which is included in the compilation of individual include programs of a program.
◉ Master programs such as class pools or function groups are organized in include programs automatically by ABAP Workbench.

4.1.1 INCLUDE

Syntax

INCLUDE incl [IF FOUND]. 

Effect

The statement INCLUDE includes the include program incl at this position in the source code. In syntax checks and when the programs is generated by ABAP Compiler, statement is replaced by the source code of the include program. The included INCLUDE program must consist of full statements.

If the specified include program does not exist, a syntax error is produced. This error message can be suppressed by specifying the addition IF FOUND.

Notes

◈ The statement INCLUDE is the only statement that can be used instead of a statement that introduces a program at the first position of a program. The requirement is that, after the include program is resolved, a statement that introduces a program is located at the beginning of the including program. 

◈ ABAP Workbench supports the automatic creation of include programs for specific program parts, such as the top include for global declarative statements. Always use the naming conventions proposed by ABAP Workbench. The top include can contain only declarative statements and is respected when individual include programs of a program are compiled. 

◈ In Repository Browser, part of Object Navigator in ABAP Workbench, the INCLUDE programs bound by a program are executed as the subnodes of the program. 

Example

These lines show the master program of the function group ABAP_DOCU. This function group displays the keyword documentation on the Application Server ABAP. It only contains INCLUDE statements which embed the actual source code. labap_docutop itself is made up of include programs for the individual declarations (global data and class declarations local to the program).

*&----------------------------------------------------------------* 
*&  Function Group SAPLABAP_DOCU 
*&----------------------------------------------------------------* 

  INCLUDE labap_docutop.               " Global Declarations 

  INCLUDE labap_docue00.               " Load of Program 

  INCLUDE labap_docuuxx.               " Function Modules 

  INCLUDE labap_docuo01.               " PBO Modules 

  INCLUDE labap_docui01.               " PAI Modules 

  INCLUDE labap_docue01.               " Handling of Runtime-Events 

  INCLUDE labap_docup01.               " Class implementations 
  INCLUDE labap_docup02. 
  INCLUDE labap_docup03. 
  INCLUDE labap_docup04. 

  INCLUDE labap_docut99.               " Unit tests 

4.2 Macros

Macros enable source code to be modularized within an ABAP program. They are

defined between the statements DEFINE and END-OF-DEFINITION and
included by their name being specified.

4.2.1 DEFINE

Syntax

DEFINE macro.
  ... &1 ... &9 ...
END-OF-DEFINITION.

Effect

The statement DEFINE defines a macro macro. The following naming conventions macro apply and ABAP words cannot be used. Macros can be defined in all program types, particularly in type groups.

Any content can be defined between the statements DEFINE and END-OF-DEFINITION. A macro is not evaluated until it is included in another program (which must have correct syntax). Currently, a macro can only be included in other ABAP programs using its name macro.

The validity of a macro is determined by its position in the compilation unit. It can be inserted at any point after END-OF-DEFINITION in the same compilation unit. If another macro is defined with the same name, it overwrites the previous macro from its new position.

Within a macro, up to nine placeholders &1 ... &9 can be used instead of ABAP words and operands. These placeholders must be replaced by fixed words when the macro is inserted.

Notes

◉ Breakpoints cannot be inserted into macros and the statements of a macro cannot be performed as individual steps in ABAP Debugger.

◉ In global classes, macros are defined in a dedicated include program.

◉ Apart from in the source code of a program and in type groups, macros can also be stored as cross-program macros in the table TRMAC. However no new macros should be defined in the table TRMAC. An example of a macro stored in the table TRMAC is break, which sets a breakpoint depending on the current user name in the system field sy-uname.

4.2.1.1 END-OF-DEFINITION

Syntax

END-OF-DEFINITION.

Effect

The statement END-OF-DEFINITION closes a macro definition that was initiated by DEFINE.

4.2.2 Including Macros

Syntax

macro [p1 p2 ... ].

Effect

If a macro is executed instead of a valid ABAP keyword, as the first word in an ABAP statement, its content is included at this position in the source text.

To ensure that the program has correct syntax, the included macro must only contain full ABAP statements (except DEFINE and END-OF-DEFINITION and introductory program statements. These statements create a source code section that is included in the current source code. The statements of a macro are not bound to the limits of processing blocks here.

Suitable ABAP words or operands p1 p2 ... must be passed to all of the placeholders of the macro. The specified operands p1 p2 ... replace the placeholders sequentially. The characters are converted to uppercase (except for the content of character literals).

ABAP Compiler searches for a macro specified in an ABAP program as follows:

1. In the preceding source text of the same compilation unit.

2. In the type groups that can be used for the program. Local macros of the program hide macros of the same name in type groups.

3. In the table TRMAC. Macros in the table TRMAC usually follow different name conventions to those in type groups and therefore nothing should be obscured.
A macro can include other macros but not itself.

Note

In global classes, macros are defined in a dedicated include program and found here.

Example

In this example, the two macros operation and output are defined. output is nested in operation. operation is called three times with different parameters. Note how the placeholders &1, &2, ... are replaced in the macros.

DATA: result TYPE i,
      n1     TYPE i VALUE 5,
      n2     TYPE i VALUE 6.

DEFINE operation.
  result = &1 &2 &3.
  output   &1 &2 &3 result.
END-OF-DEFINITION.

DEFINE output.
  write: / 'The result of &1 &2 &3 is', &4.
END-OF-DEFINITION.

operation 4 + 3.
operation 2 ** 7.
operation n2 - n1.

4.2.3 Macros

The example shows how to use and include macros.

Source Code

REPORT  DEMO_MACRO.

DATA: x TYPE i, y TYPE i, l TYPE i.

DEFINE write_frame.
  x = sy-colno. y = sy-linno.
  WRITE: '|' NO-GAP, &1 NO-GAP, '|' NO-GAP.
  l = sy-colno - x.
  y = y - 1. SKIP TO LINE y. POSITION x.
  ULINE AT x(l).
  y = y + 2. SKIP TO LINE y. POSITION x.
  ULINE AT x(l).
  y = y - 1. x = sy-colno. SKIP TO LINE y. POSITION x.
END-OF-DEFINITION.

SKIP.
write_frame 'In a frame!'.

Description

This example first defines and then uses the macro write_frame which draws a frame around the placeholder &1 on a list.

«« Previous
Next »»

No comments:

Post a Comment