ABAP Function Modules: Creating and Using Function Modules

Category
ABAP-Statements
Published
Author
Johannes

Function Modules are reusable ABAP routines with a defined interface. They are organized in Function Groups and can be RFC-enabled for remote calls.

Basic Concept

ElementDescription
Function GroupContainer for Function Modules
IMPORTINGInput parameters
EXPORTINGOutput parameters
CHANGINGInput/Output parameters
TABLESTable parameters (obsolete)
EXCEPTIONSError handling

Syntax

CALL FUNCTION 'FUNCTION_NAME'
EXPORTING
param1 = value1
IMPORTING
result = lv_result
CHANGING
data = ls_data
TABLES
itab = lt_table
EXCEPTIONS
error1 = 1
error2 = 2
OTHERS = 3.
IF sy-subrc <> 0.
" Error handling
ENDIF.

Examples

1. Calling a Function Module

DATA: lv_date_out TYPE sy-datum.
" Calculate date
CALL FUNCTION 'RP_CALC_DATE_IN_INTERVAL'
EXPORTING
date = sy-datum
days = 30
months = 0
signum = '+'
years = 0
IMPORTING
calc_date = lv_date_out.
WRITE: / 'Date + 30 days:', lv_date_out.

2. Function Module with Exceptions

DATA: lv_result TYPE p DECIMALS 2.
CALL FUNCTION 'CONVERSION_EXIT_ALPHA_INPUT'
EXPORTING
input = '123'
IMPORTING
output = lv_result
EXCEPTIONS
invalid_input = 1
OTHERS = 2.
CASE sy-subrc.
WHEN 0.
WRITE: / 'Result:', lv_result.
WHEN 1.
WRITE: / 'Invalid input'.
WHEN OTHERS.
WRITE: / 'Unknown error'.
ENDCASE.

3. Creating Your Own Function Module

" In SE37 or SE80:
" 1. Create function group: ZFGRP_CUSTOMER
" 2. Create function module: Z_CUSTOMER_GET_BY_ID
FUNCTION z_customer_get_by_id.
*"----------------------------------------------------------------------
*"*"Local Interface:
*" IMPORTING
*" VALUE(IV_KUNNR) TYPE KUNNR
*" EXPORTING
*" VALUE(ES_CUSTOMER) TYPE KNA1
*" VALUE(EV_FOUND) TYPE ABAP_BOOL
*" EXCEPTIONS
*" CUSTOMER_NOT_FOUND
*" INVALID_INPUT
*"----------------------------------------------------------------------
" Input validation
IF iv_kunnr IS INITIAL.
RAISE invalid_input.
ENDIF.
" Read customer
SELECT SINGLE * FROM kna1
WHERE kunnr = @iv_kunnr
INTO @es_customer.
IF sy-subrc = 0.
ev_found = abap_true.
ELSE.
ev_found = abap_false.
RAISE customer_not_found.
ENDIF.
ENDFUNCTION.
" Calling
DATA: ls_customer TYPE kna1,
lv_found TYPE abap_bool.
CALL FUNCTION 'Z_CUSTOMER_GET_BY_ID'
EXPORTING
iv_kunnr = '0000001000'
IMPORTING
es_customer = ls_customer
ev_found = lv_found
EXCEPTIONS
customer_not_found = 1
invalid_input = 2
OTHERS = 3.
IF sy-subrc = 0.
WRITE: / ls_customer-name1.
ENDIF.

4. RFC-Enabled Function Module

" Setting in SE37:
" Attributes -> Processing Type: Remote-Enabled Module
FUNCTION z_rfc_get_sales_data.
*"----------------------------------------------------------------------
*"*"Local Interface:
*" IMPORTING
*" VALUE(IV_VKORG) TYPE VKORG
*" VALUE(IV_DATE_FROM) TYPE SY-DATUM
*" VALUE(IV_DATE_TO) TYPE SY-DATUM
*" EXPORTING
*" VALUE(ET_ORDERS) TYPE ZTT_ORDERS
*" EXCEPTIONS
*" NO_DATA_FOUND
*" INVALID_DATE_RANGE
*"----------------------------------------------------------------------
" Validate date range
IF iv_date_from > iv_date_to.
RAISE invalid_date_range.
ENDIF.
" Read data
SELECT vbeln, erdat, kunnr, netwr
FROM vbak
WHERE vkorg = @iv_vkorg
AND erdat BETWEEN @iv_date_from AND @iv_date_to
INTO CORRESPONDING FIELDS OF TABLE @et_orders.
IF sy-subrc <> 0.
RAISE no_data_found.
ENDIF.
ENDFUNCTION.
" Remote call
CALL FUNCTION 'Z_RFC_GET_SALES_DATA'
DESTINATION 'PRD_100' " RFC Destination
EXPORTING
iv_vkorg = '1000'
iv_date_from = '20240101'
iv_date_to = '20241231'
IMPORTING
et_orders = lt_orders
EXCEPTIONS
no_data_found = 1
invalid_date_range = 2
communication_failure = 3 MESSAGE lv_msg
system_failure = 4 MESSAGE lv_msg
OTHERS = 5.
IF sy-subrc >= 3.
WRITE: / 'RFC Error:', lv_msg.
ENDIF.

5. Function Module with TABLES Parameter

" TABLES is obsolete, but still frequently used
FUNCTION z_process_items.
*"----------------------------------------------------------------------
*"*"Local Interface:
*" TABLES
*" IT_ITEMS STRUCTURE ZITEM
*" ET_RESULTS STRUCTURE ZRESULT
*"----------------------------------------------------------------------
LOOP AT it_items.
" Processing
et_results-id = it_items-id.
et_results-status = 'OK'.
APPEND et_results.
ENDLOOP.
ENDFUNCTION.
" Modern alternative: TYPE for table parameters
FUNCTION z_process_items_new.
*"----------------------------------------------------------------------
*" IMPORTING
*" VALUE(IT_ITEMS) TYPE ZTT_ITEMS
*" EXPORTING
*" VALUE(ET_RESULTS) TYPE ZTT_RESULTS
*"----------------------------------------------------------------------
LOOP AT it_items INTO DATA(ls_item).
APPEND VALUE #( id = ls_item-id status = 'OK' ) TO et_results.
ENDLOOP.
ENDFUNCTION.

6. Update Task Function Module

" For asynchronous database changes
FUNCTION z_update_customer IN UPDATE TASK.
*"----------------------------------------------------------------------
*" IMPORTING
*" VALUE(IS_CUSTOMER) TYPE KNA1
*"----------------------------------------------------------------------
MODIFY kna1 FROM is_customer.
ENDFUNCTION.
" Calling
CALL FUNCTION 'Z_UPDATE_CUSTOMER' IN UPDATE TASK
EXPORTING
is_customer = ls_customer.
" Commit executes the update
COMMIT WORK AND WAIT.

7. Function Module with Class-Based Exceptions

FUNCTION z_divide_numbers.
*"----------------------------------------------------------------------
*" IMPORTING
*" VALUE(IV_DIVIDEND) TYPE I
*" VALUE(IV_DIVISOR) TYPE I
*" EXPORTING
*" VALUE(EV_RESULT) TYPE P
*" RAISING
*" ZCX_DIVISION_BY_ZERO
*"----------------------------------------------------------------------
IF iv_divisor = 0.
RAISE EXCEPTION TYPE zcx_division_by_zero.
ENDIF.
ev_result = iv_dividend / iv_divisor.
ENDFUNCTION.
" Calling with TRY-CATCH
TRY.
CALL FUNCTION 'Z_DIVIDE_NUMBERS'
EXPORTING
iv_dividend = 100
iv_divisor = 0
IMPORTING
ev_result = lv_result.
CATCH zcx_division_by_zero INTO DATA(lx_error).
WRITE: / lx_error->get_text( ).
ENDTRY.

8. Function Group with Global Data

" TOP-Include of the function group (LZFGRP_CUSTOMERTOP)
FUNCTION-POOL zfgrp_customer.
DATA: gt_cache TYPE HASHED TABLE OF kna1 WITH UNIQUE KEY kunnr.
" Function Module uses global data
FUNCTION z_customer_get_cached.
*"----------------------------------------------------------------------
*" IMPORTING
*" VALUE(IV_KUNNR) TYPE KUNNR
*" EXPORTING
*" VALUE(ES_CUSTOMER) TYPE KNA1
*"----------------------------------------------------------------------
" First search in cache
READ TABLE gt_cache INTO es_customer
WITH KEY kunnr = iv_kunnr.
IF sy-subrc <> 0.
" Load from DB and cache
SELECT SINGLE * FROM kna1
WHERE kunnr = @iv_kunnr
INTO @es_customer.
IF sy-subrc = 0.
INSERT es_customer INTO TABLE gt_cache.
ENDIF.
ENDIF.
ENDFUNCTION.
" Clear cache
FUNCTION z_customer_clear_cache.
CLEAR gt_cache.
ENDFUNCTION.

9. Dynamic Function Module Call

DATA: lv_funcname TYPE funcname VALUE 'Z_CUSTOMER_GET_BY_ID',
lt_params TYPE abap_func_parmbind_tab,
lt_excps TYPE abap_func_excpbind_tab,
ls_customer TYPE kna1,
lv_kunnr TYPE kunnr VALUE '0000001000'.
" Build parameters
lt_params = VALUE #(
( name = 'IV_KUNNR'
kind = abap_func_exporting
value = REF #( lv_kunnr ) )
( name = 'ES_CUSTOMER'
kind = abap_func_importing
value = REF #( ls_customer ) )
).
lt_excps = VALUE #(
( name = 'CUSTOMER_NOT_FOUND' value = 1 )
( name = 'OTHERS' value = 99 )
).
" Dynamic call
CALL FUNCTION lv_funcname
PARAMETER-TABLE lt_params
EXCEPTION-TABLE lt_excps.
IF sy-subrc = 0.
WRITE: / ls_customer-name1.
ENDIF.

10. Testing Function Module (SE37)

" In SE37:
" 1. Open function module
" 2. Menu: Function Module -> Test -> Single Test
" 3. Enter parameters
" 4. F8 to execute
" Or programmatically with Unit Test
CLASS ltcl_function_test DEFINITION FOR TESTING
DURATION SHORT RISK LEVEL HARMLESS.
PRIVATE SECTION.
METHODS: test_customer_get FOR TESTING.
ENDCLASS.
CLASS ltcl_function_test IMPLEMENTATION.
METHOD test_customer_get.
DATA: ls_customer TYPE kna1,
lv_found TYPE abap_bool.
CALL FUNCTION 'Z_CUSTOMER_GET_BY_ID'
EXPORTING
iv_kunnr = '0000001000'
IMPORTING
es_customer = ls_customer
ev_found = lv_found
EXCEPTIONS
OTHERS = 1.
cl_abap_unit_assert=>assert_equals(
exp = 0
act = sy-subrc
msg = 'Function should succeed'
).
cl_abap_unit_assert=>assert_true(
act = lv_found
msg = 'Customer should be found'
).
ENDMETHOD.
ENDCLASS.

11. Function Module Documentation

" In SE37:
" Menu: Goto -> Documentation
" Structured documentation:
" - Short description
" - Parameter documentation
" - Example call
" - Exceptions explained
" Documentation in code (for developers)
FUNCTION z_well_documented.
*"----------------------------------------------------------------------
*" Description:
*" Calculates the total price including VAT
*"
*" Parameters:
*" IV_AMOUNT - Net amount
*" IV_TAX_RATE - Tax rate in percent (e.g., 19)
*" EV_TOTAL - Gross amount
*"
*" Exceptions:
*" INVALID_AMOUNT - Amount is negative
*" INVALID_TAX_RATE - Tax rate outside 0-100
*"
*" Example:
*" CALL FUNCTION 'Z_WELL_DOCUMENTED'
*" EXPORTING iv_amount = 100 iv_tax_rate = 19
*" IMPORTING ev_total = lv_total.
*" " lv_total = 119.00
*"----------------------------------------------------------------------
" Implementation...
ENDFUNCTION.

12. Conversion Exits

" Special Function Modules for formatting
" Naming convention: CONVERSION_EXIT_<NAME>_INPUT/OUTPUT
FUNCTION conversion_exit_alpha_input.
*" Add leading zeros
*" IMPORTING VALUE(INPUT)
*" EXPORTING VALUE(OUTPUT)
CALL FUNCTION 'CONVERSION_EXIT_ALPHA_INPUT'
EXPORTING input = '1000'
IMPORTING output = lv_kunnr.
" lv_kunnr = '0000001000'
ENDFUNCTION.
FUNCTION conversion_exit_alpha_output.
*" Remove leading zeros
CALL FUNCTION 'CONVERSION_EXIT_ALPHA_OUTPUT'
EXPORTING input = '0000001000'
IMPORTING output = lv_display.
" lv_display = '1000'
ENDFUNCTION.

13. Popup Function Modules

" Yes/No Popup
DATA: lv_answer TYPE c LENGTH 1.
CALL FUNCTION 'POPUP_TO_CONFIRM'
EXPORTING
titlebar = 'Confirmation'
text_question = 'Do you want to continue?'
text_button_1 = 'Yes'
text_button_2 = 'No'
default_button = '2'
display_cancel_button = abap_false
IMPORTING
answer = lv_answer.
IF lv_answer = '1'.
" Yes selected
ENDIF.
" Text input
DATA: lv_input TYPE string.
CALL FUNCTION 'POPUP_GET_VALUES'
EXPORTING
popup_title = 'Input'
TABLES
fields = lt_fields.
" Display message
CALL FUNCTION 'POPUP_TO_DISPLAY_TEXT'
EXPORTING
titel = 'Information'
textline1 = 'Processing completed.'
textline2 = '100 records processed.'.

14. Background Processing

" Function Module for background job
FUNCTION z_batch_process.
*"----------------------------------------------------------------------
*" IMPORTING
*" VALUE(IV_DATE) TYPE SY-DATUM
*"----------------------------------------------------------------------
" Can be executed in background job
" No dialog calls!
SELECT * FROM vbak
WHERE erdat = @iv_date
INTO TABLE @DATA(lt_orders).
LOOP AT lt_orders INTO DATA(ls_order).
" Processing without user interaction
ENDLOOP.
ENDFUNCTION.
" Schedule as job
SUBMIT zreport_calling_function
VIA JOB lv_jobname NUMBER lv_jobcount
AND RETURN.

15. Wrapper Class for Function Modules

CLASS zcl_function_wrapper DEFINITION.
PUBLIC SECTION.
" Type-safe wrappers for frequently used FMs
CLASS-METHODS: convert_to_internal
IMPORTING iv_external TYPE clike
RETURNING VALUE(rv_internal) TYPE kunnr.
CLASS-METHODS: convert_to_external
IMPORTING iv_internal TYPE kunnr
RETURNING VALUE(rv_external) TYPE string.
CLASS-METHODS: calculate_date
IMPORTING iv_date TYPE sy-datum
iv_days TYPE i DEFAULT 0
iv_months TYPE i DEFAULT 0
iv_years TYPE i DEFAULT 0
RETURNING VALUE(rv_date) TYPE sy-datum.
ENDCLASS.
CLASS zcl_function_wrapper IMPLEMENTATION.
METHOD convert_to_internal.
CALL FUNCTION 'CONVERSION_EXIT_ALPHA_INPUT'
EXPORTING input = iv_external
IMPORTING output = rv_internal.
ENDMETHOD.
METHOD convert_to_external.
CALL FUNCTION 'CONVERSION_EXIT_ALPHA_OUTPUT'
EXPORTING input = iv_internal
IMPORTING output = rv_external.
ENDMETHOD.
METHOD calculate_date.
DATA: lv_sign TYPE c LENGTH 1.
" Positive or negative
IF iv_days >= 0 AND iv_months >= 0 AND iv_years >= 0.
lv_sign = '+'.
ELSE.
lv_sign = '-'.
ENDIF.
CALL FUNCTION 'RP_CALC_DATE_IN_INTERVAL'
EXPORTING
date = iv_date
days = abs( iv_days )
months = abs( iv_months )
signum = lv_sign
years = abs( iv_years )
IMPORTING
calc_date = rv_date.
ENDMETHOD.
ENDCLASS.
" Usage
DATA(lv_kunnr) = zcl_function_wrapper=>convert_to_internal( '1000' ).
DATA(lv_next_month) = zcl_function_wrapper=>calculate_date(
iv_date = sy-datum
iv_months = 1
).

Important Transactions

TransactionDescription
SE37Function Builder
SE80Repository Browser
SM59RFC Destinations

Important Notes / Best Practice

  • Organize Function Groups logically by topic.
  • Use VALUE() for IMPORTING parameters (by Value).
  • Only make RFC-enabled when really necessary (performance).
  • Avoid TABLES – use TYPE for tables instead.
  • Define Exceptions for all error cases.
  • Maintain Documentation in SE37.
  • Use Global Data in function group for caching.
  • Use Class-based Exceptions for OO integration.
  • No dialogs in RFC-enabled modules.
  • Combine with BAPI Development for APIs.