Show TOC

Extracting Methods from ExpressionsLocate this document in the navigation structure

Context

In the implementation part of an ABAP class, you can create a new method that returns the result of a selected expression. The tool declares this returning parameter with type Integer and the selected expression is replaced with a call to the new method.

Note The editor only replaces the selected expression. If the same expression is used several times in the same repository object, only the selected occurrence is replaced. This means you have to extract all remaining occurrences individually.

Example

Here, the expression length * width is extracted into a method:

CLASS CL_METHOD_CHECK_AREA DEFINITION PUBLIC. 
 " This class describes the 'length * width' extraction of an expression to a new method 
 PUBLIC SECTION. 
  DATA: 
   length TYPE i, 
   width TYPE i. 
  METHODS: 
   check_area 
    RETURNING 
     VALUE(r_result) TYPE abap_bool. 
ENDCLASS. 
 
CLASS CL_METHOD_CHECK_AREA IMPLEMENTATION. 
 METHOD check_area. 
  IF length * width > 100. 
   r_result = abap_false. 
  ELSE. 
   r_result = abap_true. 
  ENDIF. 
 ENDMETHOD. 
ENDCLASS.

Procedure

  1. In the implementation part, select the entire expression that you want to add to a new method.
  2. In the context menu, choose Quick Fix or use the shortcut (Ctrl 1).
  3. In the Quick Fix dialog box, double-click Extract method from expression.

Results

The extracted method is created with the name new_method.

In the private section of the definition part, the name of the extracted method (new_method) is added and the appropriate parameters are declared.

In the implementation part, the selected expression is added in a new method. In the former call, the expression is replaced with the name of the extracted method (new_method).

Example

ABAP class after extraction:

CLASS CL_METHOD_CHECK_AREA DEFINITION PUBLIC. 
 "This class describes the 'length * width' extraction of an expression for a new method. 
 PUBLIC SECTION. 
  DATA: 
   length TYPE i, 
   width TYPE i. 
  METHODS: 
   check_area 
    RETURNING 
     VALUE(r_result) TYPE abap_bool. 
PRIVATE SECTION. 
  METHODS: new_method 
   RETURNING 
    VALUE(r_result) TYPE i.
ENDCLASS.
 
CLASS CL_METHOD_CHECK_AREA IMPLEMENTATION.
 METHOD check_area. 
  IF new_method( ) > 100. 
   r_result = abap_false. 
  ELSE. 
   r_result = abap_true. 
  ENDIF. 
 ENDMETHOD. 
METHOD new_method.
  r_result = length * width.
 ENDMETHOD.
ENDCLASS.