Modularization Overview

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

A program that does everything in one long list of statements is hard to read, hard to test and impossible to reuse. Modularization means cutting the program into named pieces, each with one job, that other code can call. ABAP offers several kinds of piece, built over four decades, and a newcomer meets all of them: the old report in front of you probably uses FORM blocks and a macro, the standard SAP function you call is a function module, and the new code you write is a method. This page explains what each kind is, why methods are the one to choose, the few cases where a function module is still required, and why FORM subroutines and DEFINE macros are obsolete. It finishes by turning a FORM into a method step by step. It is written against Standard ABAP release 8.16 and ABAP for Cloud Development release 9.20 (2608). Methods apply everywhere: ABAP Cloud, classic Standard ABAP, on premise and in the Public Edition. Function modules can be called from ABAP Cloud, but writing new ones is for classic Standard ABAP and the special cases below. FORM, PERFORM and DEFINE are classic Standard ABAP only; the ABAP Cloud Keyword Documentation marks FORM and PERFORM as obsolete and deprecated, supported only temporarily and to be replaced, and has no page for DEFINE.

Before you read

Key terms

  • Processing block: a unit of code that the ABAP runtime starts as a whole, such as a method, a function module, a subroutine or an event block.

  • Method: a named block of code of a class, with its own parameters and its own local data.

  • Function module: a reusable procedure that lives in a function group and is called by name with CALL FUNCTION.

  • Subroutine: an obsolete procedure written between FORM and ENDFORM and called with PERFORM.

  • Macro: a named piece of source text, defined between DEFINE and END-OF-DEFINITION, that the compiler pastes in wherever the name is used.

  • Parameter interface: the list of values a procedure takes in and gives back, each with a name and a type.

The kinds of modularization

ABAP has two groups of building blocks. The first group is procedures: processing blocks that have a parameter interface (the values that go in and come out) and their own local data, so that they can be called from other code. The Keyword Documentation names three kinds.

  • A method belongs to a class. It is the standard procedure of modern ABAP.

  • A function module belongs to a function group, which is a container for related function modules and the data they share. Function modules were the reusable unit of ABAP before classes existed, and SAP still ships thousands of them.

  • A subroutine is a block between FORM and ENDFORM, called with PERFORM. It was the way to split up a program before ABAP Objects. The Keyword Documentation lists it as the obsolete kind of procedure.

The second group changes how the source text is organised and does not create a callable unit at runtime.

  • An include program is a piece of source text that other programs pull in with INCLUDE, mostly to split a large program or a function group into several files. Function groups and global classes use includes internally, and you rarely create one yourself in new code.

  • A macro is a piece of source text with placeholders that the compiler inserts where the macro name appears. It is covered below as obsolete.

The rule that ties these together comes from SAP’s own programming guidelines in the Keyword Documentation: use function modules and subroutines only where they are technically necessary, and even then do not put the real logic in them. Put the logic in a method and let the function module or subroutine only call it. The next sections show why and where the exceptions are.

flowchart TD A[New piece of logic to reuse] --> B{Does the platform force a function module or a subroutine?} B -- No --> C[Write a method in a class] B -- RFC, update module or classic screen --> D[Function module that only calls a method] B -- PERFORM ON COMMIT or GENERATE SUBROUTINE POOL --> E[FORM that only calls a method] C --> F[Repeated code snippet? Still a method, not a macro]

Methods first

A method is declared in the definition of a class and implemented in the implementation of the class, so the interface and the code are kept apart. Its parameter interface has four kinds of parameter, each given by keyword and name: IMPORTING values go in, EXPORTING values come out, CHANGING values go in and come out, and RETURNING gives back exactly one result that the caller can use directly inside an expression. A method that has a RETURNING parameter is called a functional method, and total( items ) can then stand wherever a value is expected. Parameters can be typed completely, can be optional or have default values, and are passed by name, which is why a call reads check->total( items ) or NEW lcl_claim_check( iv_limit = '200.00' ) and does not depend on the order of the arguments.

Methods also solve problems that the older kinds had. Code in a method belongs to a class, so what is public, protected or private is decided on purpose. A method can be tested on its own with ABAP Unit. Methods can raise class-based exceptions and be redefined in subclasses. The full syntax is on the page Classes and Objects, and errors are covered in Class-Based Exceptions.

Function modules where the platform requires them

A function module is written between FUNCTION and ENDFUNCTION in a function group, and it is called with CALL FUNCTION and the module name. The Keyword Documentation says that you may create function modules only when a method technically cannot do the job. Three cases remain.

  • Remote function call (RFC). A function module marked as remote-enabled can be called from another system, from a non-ABAP program or in a separate session on the same system. A remote-enabled module has to pass all its parameters by value. Methods of classes cannot be called remotely this way.

  • Update function modules. The statement CALL FUNCTION ... IN UPDATE TASK registers a function module to run later, when COMMIT WORK ends the SAP LUW (SAP logical unit of work, the group of database changes that is saved together or not at all). This is the classic way to put database changes of a business transaction into the update task, and only function modules can be registered for it.

  • Access to classic dynpros and selection screens. Classic screens and the selection screens of a function group belong to the function group, so the module that shows them has to live there.

The rule for such a module is to keep the module as thin as possible. The module receives its parameters and calls a method, and everything that decides anything lives in the class behind it. An example for the Expense claims application follows. It requires an SAP system; not run here.

FUNCTION z_exp_check_claim.
*"----------------------------------------------------------------------
*"  IMPORTING
*"     VALUE(IV_LIMIT) TYPE  ZEXP_AMOUNT
*"     VALUE(IT_ITEMS) TYPE  ZEXP_ITEMS
*"  EXPORTING
*"     VALUE(EV_OK) TYPE  ABAP_BOOL
*"----------------------------------------------------------------------
  " the module only wraps a call: the logic is in the method
  ev_ok = NEW zcl_exp_claim_check( iv_limit )->is_within_limit( it_items ).
ENDFUNCTION.

The names ZEXP_AMOUNT, ZEXP_ITEMS and ZCL_EXP_CLAIM_CHECK are objects of the running Expense claims example and are not delivered by SAP. The parameter interface of a function module is maintained in the Function Builder (transaction SE37) or in ABAP Development Tools, and the system writes it as the comment lines under FUNCTION. Function groups, interfaces with TABLES and classic exceptions, and how to test a module in SE37 are the subject of the next page, which is named Function Modules and Function Groups.

In ABAP Cloud, function modules can technically be used, but they are not recommended for new implementations, and many features that function groups rely on, such as dynpro-related ones, are not compatible with the restricted language.

Subroutines with FORM and PERFORM

A subroutine is a block of statements between FORM and ENDFORM. It is started with PERFORM and the name. Before ABAP Objects existed this was how a program was split into parts, and it is the first thing you meet in old reports. Internally a subroutine can read and change every global variable of its program, which makes it easy to write and hard to understand: nothing in the call line tells you what it changes.

The Keyword Documentation says that subroutines should no longer be created in new programs and gives the reasons, which are weaknesses of the parameter interface and of the way a subroutine is reached.

  • Parameters are positional: the order in the PERFORM line must match the order after FORM, and no name helps you check it. A method call uses names.

  • There is no real input parameter when a value is passed by reference. Passing by reference is the default, and then a parameter listed after USING is not protected: changing it in the subroutine changes the caller’s variable.

  • Typing is optional. An untyped parameter takes the fully generic type any, so mistakes show up at runtime and not at the syntax check.

  • There are no optional parameters.

  • Every subroutine is part of the public interface of its program, so another program can call it with PERFORM ... IN PROGRAM, whether or not you wanted that. Such external calls are critical, because which program group of the internal session the code belongs to cannot be fixed statically.

The following small report shows the second weakness. The subroutine is declared with USING, which suggests that the value only goes in, but the global variable has changed after the call. It runs in the local playground and prints after bump: 6.

REPORT zmod_weak.

DATA gv_n TYPE i VALUE 5.

START-OF-SELECTION.
  PERFORM bump USING gv_n.
  WRITE / |after bump: { gv_n }|.

FORM bump USING p_n TYPE i.
  p_n = p_n + 1.
ENDFORM.

Writing USING VALUE(p_n) instead makes the subroutine work on a copy, and the caller’s variable would stay 5. The local playground does not implement that copy, so this variant is described from the Keyword Documentation and not run here. CHANGING parameters differ from USING parameters only in intent: both are by reference unless VALUE is written. A third form, TABLES, passes an internal table together with a header line and is obsolete as well.

Two situations still force a subroutine, and the guideline for both is the same as for function modules: the subroutine only wraps a method call.

  • PERFORM subr ON COMMIT and PERFORM subr ON ROLLBACK register a subroutine to run when COMMIT WORK or ROLLBACK WORK ends the SAP LUW. A registered subroutine cannot have parameters, so it receives data only through something global such as ABAP memory, and it suits cleanup better than database changes.

  • GENERATE SUBROUTINE POOL builds a program at runtime that holds subroutines.

The example registers a wrapper whose body is a single method call. It requires an SAP system; not run here.

" classic report: the FORM only calls the method
FORM on_commit.
  zcl_exp_claim_cleanup=>run( ).
ENDFORM.

" somewhere in the program, before COMMIT WORK
PERFORM on_commit ON COMMIT.

When you maintain an old program, subroutines that already exist for the internal structure of the program may stay and may still be called. Avoid new external calls from other programs.

Macros with DEFINE

A macro is source text under a name. DEFINE name. followed by statements and END-OF-DEFINITION. stores the text, and up to nine placeholders written &1 to &9 stand for the words that follow the name when the macro is used. A macro has no parameter interface, no local data and no type checking of its own. The Keyword Documentation says that a macro is not evaluated until it is used, and then it must have correct syntax, so a mistake in it only shows where it is used. You also cannot set a breakpoint inside a macro or step through its statements in the debugger.

The example defines a macro that adds a number to a variable and uses it twice. It runs in the local playground and prints total 15.

REPORT zmod_macro.

DEFINE add_to_total.
  &1 = &1 + &2.
END-OF-DEFINITION.

DATA gv_total TYPE i.

START-OF-SELECTION.
  add_to_total gv_total 10.
  add_to_total gv_total 5.
  WRITE / |total { gv_total }|.

The Keyword Documentation says to use macros only in exceptional cases. A method does the same job with a typed interface, a debugger and a test. Cross-program macros stored in the table TRMAC should not be created at all; the documented example there is break, which you may still see in old code, and which sets a breakpoint depending on the current user. You will meet macros most often in old programs and in some classic SAP code, for example in the HR logical databases that later pages describe.

Refactoring a FORM into a method

The Expense claims example needs to add up the items of a claim and check the sum against a limit. The first listing is how an old report would do it, with global variables and a subroutine. It runs in the local playground and prints total 155.50 within limit: X, where X is the value of abap_true.

REPORT zmod_before.

TYPES ty_amount TYPE p LENGTH 8 DECIMALS 2.
TYPES: BEGIN OF ty_item,
         item_no  TYPE i,
         category TYPE c LENGTH 12,
         amount   TYPE ty_amount,
       END OF ty_item.
TYPES ty_items TYPE STANDARD TABLE OF ty_item WITH EMPTY KEY.

DATA gt_items TYPE ty_items.
DATA gv_limit TYPE ty_amount VALUE '200.00'.
DATA gv_total TYPE ty_amount.
DATA gv_ok    TYPE abap_bool.

START-OF-SELECTION.
  gt_items = VALUE #( ( item_no = 1 category = 'TRAVEL' amount = '120.50' )
                      ( item_no = 2 category = 'MEALS'  amount = '35.00' ) ).
  PERFORM check_claim USING gt_items gv_limit
                      CHANGING gv_total gv_ok.
  WRITE / |total { gv_total } within limit: { gv_ok }|.

FORM check_claim USING    it_items TYPE ty_items
                          iv_limit TYPE ty_amount
                 CHANGING cv_total TYPE ty_amount
                          cv_ok    TYPE abap_bool.
  DATA ls_item TYPE ty_item.
  CLEAR cv_total.
  LOOP AT it_items INTO ls_item.
    cv_total = cv_total + ls_item-amount.
  ENDLOOP.
  IF cv_total <= iv_limit.
    cv_ok = abap_true.
  ELSE.
    cv_ok = abap_false.
  ENDIF.
ENDFORM.

The refactoring takes five steps. Each one removes a weakness named above.

  1. Find what the subroutine reads and writes. Here it reads the items and the limit, and it writes the total and the flag. Everything it touches is in the parameter list, so no hidden global is involved.

  2. Decide what is configuration and what is input. The limit does not change between calls, so it becomes a parameter of the constructor and an attribute of the class. The items change with every call, so they stay an IMPORTING parameter.

  3. Turn each output into a RETURNING value. The total becomes the result of the method total. The flag is not stored anywhere any more: the method is_within_limit works it out from the total, so no caller can set it to something that disagrees with the items.

  4. Replace the PERFORM line by method calls, and the global variables by local ones or by inline declarations.

  5. If another program still performs the subroutine with PERFORM ... IN PROGRAM, leave a FORM that only calls the method, and remove it when the last caller is changed.

The result is a local class that does the same job. It runs in the local playground and prints the same line, total 155.50 within limit: X. In a real system the class would be a global class created in ABAP Development Tools, which also lets other programs and ABAP Unit tests use it.

REPORT zmod_after.

TYPES ty_amount TYPE p LENGTH 8 DECIMALS 2.
TYPES: BEGIN OF ty_item,
         item_no  TYPE i,
         category TYPE c LENGTH 12,
         amount   TYPE ty_amount,
       END OF ty_item.
TYPES ty_items TYPE STANDARD TABLE OF ty_item WITH EMPTY KEY.

CLASS lcl_claim_check DEFINITION FINAL.
  PUBLIC SECTION.
    METHODS constructor
      IMPORTING iv_limit TYPE ty_amount.
    METHODS total
      IMPORTING it_items        TYPE ty_items
      RETURNING VALUE(rv_total) TYPE ty_amount.
    METHODS is_within_limit
      IMPORTING it_items     TYPE ty_items
      RETURNING VALUE(rv_ok) TYPE abap_bool.
  PRIVATE SECTION.
    DATA mv_limit TYPE ty_amount.
ENDCLASS.

CLASS lcl_claim_check IMPLEMENTATION.
  METHOD constructor.
    mv_limit = iv_limit.
  ENDMETHOD.

  METHOD total.
    LOOP AT it_items INTO DATA(ls_item).
      rv_total = rv_total + ls_item-amount.
    ENDLOOP.
  ENDMETHOD.

  METHOD is_within_limit.
    rv_ok = xsdbool( total( it_items ) <= mv_limit ).
  ENDMETHOD.
ENDCLASS.

START-OF-SELECTION.
  DATA(items) = VALUE ty_items( ( item_no = 1 category = 'TRAVEL' amount = '120.50' )
                                ( item_no = 2 category = 'MEALS'  amount = '35.00' ) ).
  DATA(check) = NEW lcl_claim_check( iv_limit = '200.00' ).
  WRITE / |total { check->total( items ) } within limit: { check->is_within_limit( items ) }|.

The call in the last line now reads as a sentence, the limit is fixed when the object is created, the item list is the only thing passed per call, and the class can be tested by creating it with a different limit. Comparing the two listings, the subroutine needed four parameters and two global variables, while the method needs one input and returns one value.

The table collects the correspondence for other refactorings.

Old form Modern form What changes

PERFORM subr USING a CHANGING b

b = obj->method( a ) with a RETURNING parameter

Output becomes the return value; the call is named and typed.

Global variable read by a FORM

Constructor parameter and attribute, or an IMPORTING parameter

The dependency is visible in the interface.

FORM ... TABLES itab

IMPORTING or CHANGING parameter typed as a table type

No header line; the table has a declared type.

DEFINE ... END-OF-DEFINITION macro

A method, or an inline expression

The code gets types, a debugger and tests.

CALL FUNCTION ... EXCEPTIONS for new code

A method that raises a class-based exception

The error is a typed object and cannot be forgotten silently.

Older material you may meet

Programs and books written before ABAP Objects, and many written for the first releases that had it, use FORM and PERFORM as the normal way to split a program, put the main logic into a function module, and use macros to avoid typing the same lines. That is the reason these three forms still turn up everywhere in the code of SAP customers and in the code that SAP itself has not yet modernised. Reading them is part of the job. What has changed is the advice for new code: the Keyword Documentation now treats methods as the only kind of procedure that holds real logic, and treats the other two kinds as wrappers that the platform requires in a few places. If a book shows a new function module with several hundred lines, write the logic in a class instead and keep the function module as the thin entry point.

Summary

  • Modularization splits a program into named pieces. ABAP has methods, function modules and subroutines as procedures, and include programs and macros as ways to organise source text.

  • Use methods for all new logic. They have named, typed parameters, a RETURNING value, visibility, exceptions and tests.

  • A function module is still required for RFC, for update function modules and for classic screens in function groups; keep it thin and let it call a method.

  • FORM and PERFORM are obsolete and DEFINE macros are for exceptional cases only. A subroutine is still needed for PERFORM ... ON COMMIT and GENERATE SUBROUTINE POOL, and there it only wraps a method call.

  • To refactor a FORM, turn parameters that stay the same into constructor parameters, turn outputs into RETURNING values and replace the PERFORM line by a method call.