SAP LOCAL DECLAR - Guide
Get Example source ABAP code based on a different SAP table
Local Declarations
ABAP_BACKGROUND
Local declarations can be made in a procedure (
Procedure-local declarations can be specified in any position of a procedure. However, the position of the declaration does not affect the validity area of the declared object (which always comprises the entire procedure), but only the static visibility.
ABAP_RULE
Position the local declarations of a procedure (
ABAP_DETAILS
Local declarations within a procedure (
FIELD-SYMBOLS < field_symbol> TYPE any.
...
* ASSIGN dobj TO < field_symbol>. 'Syntax error ...
ASSIGN ('DOBJ') TO < field_symbol>. 'No error
ASSERT < field_symbol> IS ASSIGNED.
...
DATA dobj TYPE i.
ENDMETHOD.>
Because the different behavior of the
This rule contradicts the common recommendations for other programming languages. They recommend declaring local variables as close to their use as possible to tightly restrict their validity area. In ABAP, however, there is no block-local validity of local variables. Positioning a declaration within the statement block of a loop, for example, does not make it possible to restrict the validity of this declaration to this statement block. Rather, the variable is valid within the entire procedure. So a declaration at the position where it is used can be misleading to developers or readers of a program who are not aware of this.
According to the rule,
Note
Within processing blocks that do not support any local data (dialog modules and event blocks), declarative statements must be
In
Exception
ABAP_EXAMPLE_BAD
The following source code shows a local data declaration in a loop. Readers who are familiar with another programming language or even developers of the program themselves would probably expect the
...
DO 10 TIMES.
DATA number TYPE i VALUE 10.
...
'number = 11, 13, 16, 20, ...
number = number + sy-index.
...
ENDDO.
...
ENDMETHOD.>
ABAP_EXAMPLE_END
ABAP_EXAMPLE_GOOD
The following source code shows the corrected version of the above example, which behaves as the above example is expected to behave (if deeper ABAP knowledge is not involved). There is no block-local validity of data in ABAP, so proceed as shown below.
DATA number TYPE i.
...
DO 10 TIMES.
number = 10.
...
'number = 11, 12, 13, 14, ...
number = number + sy-index.
...
ENDDO.
...
ENDMETHOD.>
ABAP_EXAMPLE_END