ABAP Keyword Documentation →  ABAP Programming Guidelines →  Robust ABAP →  Data Types and Data Objects → 

Inline Declarations

Background

The declaration operators

can be used to make inline declarations in writer positions. In this way, declarations are made in operational statements rather than in declaration statements. The declaration is made when the program is compiled, regardless of whether the statement is actually executed.

Rule

Only use inline declarations locally

Only make inline declarations in processing blocks that support local data. Use them as if they were local declarations in the current statement block.

Details

If used correctly, inline declarations are an excellent way of making programs leaner and easier to understand. However, since they they are used with a directly prefixed declaration statement (like the short forms of the statement where they are specified), the guidelines for declaration statements must be followed.

Bad example

Inline declaration of a field symbol <pattern> and two variables moff and mlen in a LOOP and their later reuse in a different loop. At first glance, it appears that the declarations are only valid in the first loop and only conditionally, but they are valid for the whole method and unconditionally.

METHOD demo_method.
  "IMPORTING i_tab1 TYPE TANDARD TABLE OF string
  "IMPORTING i_tab2 TYPE TANDARD TABLE OF string
  "IMPORTING i_text TYPE string

  IF i_tab1 IS NOT INITIAL.
    LOOP AT i_tab1 ASSIGNING FIELD-SYMBOL(<pattern>).
      FIND <pattern> IN i_text MATCH OFFSET DATA(moff)
                               MATCH LENGTH DATA(mlen).
      ...
    ENDLOOP.
  ENDIF.

  IF i_tab2 IS NOT INITIAL.
    LOOP AT i_tab2 ASSIGNING <pattern>.
      FIND <pattern> IN i_text MATCH OFFSET moff
                               MATCH LENGTH mlen.
      ...
    ENDLOOP.
  ENDIF.

ENDMETHOD.

Good example

The field symbols and variables declared inline are only used locally in the their respective loops. The fact that they are valid in the whole method is ignored, for the sake of simplicity. If the field symbol and the variables are only to be declared once for both loops, they should be declared at the start of the method using declaration statements.

METHOD demo_method.
  "IMPORTING i_tab1 TYPE TANDARD TABLE OF string
  "IMPORTING i_tab2 TYPE TANDARD TABLE OF string
  "IMPORTING i_text TYPE string

  IF i_tab1 IS NOT INITIAL.
    LOOP AT i_tab1 ASSIGNING FIELD-SYMBOL(<pattern1>).
      FIND <pattern1> IN i_text MATCH OFFSET DATA(moff1)
                                MATCH LENGTH DATA(mlen1).
      ...
    ENDLOOP.
  ENDIF.

  IF i_tab2 IS NOT INITIAL.
    LOOP AT i_tab2 ASSIGNING FIELD-SYMBOL(<pattern2>.
      FIND <pattern2> IN i_text MATCH OFFSET DATA(moff2)
                                MATCH LENGTH DATA(mlen2).
      ...
    ENDLOOP.
  ENDIF.

ENDMETHOD.