In ABAP (Advanced Business Application Programming), functions and subroutines are modular programming constructs that allow you to encapsulate and reuse code. They help improve code readability, maintainability, and reusability. Here's an overview of ABAP functions and subroutines:
1. Functions:
Functions in ABAP are modular units of code that perform a specific task and return a value. They are defined with the FUNCTION keyword and can be called from within other ABAP programs or functions. Functions are particularly useful for performing calculations and transformations.
Defining a Function:
FUNCTION calculate_total. PARAMETERS: p_quantity TYPE i, p_price TYPE p DECIMALS 2.
DATA lv_total TYPE p DECIMALS 2. lv_total = p_quantity * p_price.
CALL FUNCTION 'DISPLAY_TOTAL' EXPORTING total = lv_total. ENDFUNCTION.
Calling a Function:
DATA lv_quantity TYPE i VALUE 10. DATA lv_price TYPE p DECIMALS 2 VALUE '25.50'.
CALL FUNCTION 'CALCULATE_TOTAL' EXPORTING p_quantity = lv_quantity p_price = lv_price.
2. Subroutines:
Subroutines, also known as FORM routines in ABAP, are modular units of code that perform a specific task but do not return a value. They are defined with the FORM keyword and are typically used for performing actions or calculations within a program or function.
Defining a Subroutine:
FORM calculate_discount USING p_amount TYPE p DECIMALS 2 CHANGING p_discount TYPE p DECIMALS 2.
DATA lv_order_total TYPE p DECIMALS 2 VALUE '125.75'. DATA lv_discount TYPE p DECIMALS 2.
PERFORM calculate_discount USING lv_order_total CHANGING lv_discount.
3. Differences Between Functions and Subroutines:
Return Value: Functions return a value, whereas subroutines do not.
Calling Convention: Functions are called using the CALL FUNCTION statement, whereas subroutines are called using the PERFORM statement.
Parameters: Functions use the EXPORTING keyword to pass parameters to the function, and the result is returned in a defined parameter. Subroutines use the USING keyword to pass parameters, and any changes to parameters are reflected outside the subroutine using the CHANGING keyword.
Visibility: Functions can be called from other programs or functions and can be used as standalone modules. Subroutines are typically used within the same program or function in which they are defined.
4. Guidelines for Functions and Subroutines:
Use functions for calculations and transformations that return a result.
Use subroutines for performing actions within a program or function.
Keep functions and subroutines small and focused on a specific task.
Use meaningful names for functions and subroutines to improve code readability.
Document functions and subroutines to explain their purpose and usage.