1.24 SAP ABAP - Subroutines

«« Previous
Next »»

A subroutine is a reusable section of code. It is a modularization unit within the program where a function is encapsulated in the form of source code. You page out a part of a program to a subroutine to get a better overview of the main program, and to use the corresponding sequence of statements many times as depicted in the following diagram.

SAP ABAP - Subroutines

We have program X with 3 different source code blocks. Each block has the same ABAP statements. Basically, they are the same code blocks. To make this code easier to maintain, we can encapsulate the code into a subroutine. We can call this subroutine in our programs as many times as we wish. A subroutine can be defined using Form and EndForm statements.

Following is the general syntax of a subroutine definition.

FORM <subroutine_name>.
<statements> 
ENDFORM.

We can call a subroutine by using PERFORM statement. The control jumps to the first executable statement in the subroutine <subroutine_name>. When ENDFORM is encountered, control jumps back to the statement following the PERFORM statement.

Example

Step 1 − Go to transaction SE80. Open the existing program and then right-click on program. In this case, it is 'ZSUBTEST'.

Step 2 − Select Create and then select Subroutine. Write the subroutine name in the field and then click the continue button. The subroutine name is 'Sub_Display' as shown in the following screenshot.

SAP ABAP - Subroutines

Step 3 − Write the code in FORM and ENDFORM statement block. The subroutine has been created successfully.

We need to include PERFORM statement to call the subroutine. Let’s take a look at the code −

REPORT ZSUBTEST. 
PERFORM Sub_Display.

* Form Sub_Display 
* -->  p1 text 
* <--  p2 text 

FORM Sub_Display. 
Write: 'This is Subroutine'. 
Write: / 'Subroutine created successfully'. 
ENDFORM.                    " Sub_Display

Step 4 − Save, activate and execute the program. The above code produces the following output −

Subroutine Test:
This is Subroutine
Subroutine created successfully

Hence, using subroutines makes your program more function-oriented. It splits the program's task into sub-functions, so that each subroutine is responsible for one subfunction. Your program becomes easier to maintain as changes to functions often only have to be implemented in the subroutine.

«« Previous
Next »»

No comments:

Post a Comment