Dev Tip: Take back program space and reduce unneeded repetition in your ABAP code with inline DATA and FIELD-SYMBOLS declarations.
In case you’ve missed our dev tips in the past weeks, we will be posting them in the blog moving forward. To sign up and get your dev tips delivered to your inbox each week, click here!
Tip of the Week
Take back program space and reduce unneeded repetition in your ABAP code with inline DATA and FIELD-SYMBOLS declarations.
Unless you’re being sent into the past to be eliminated by a younger version of yourself, you probably enjoy loops. They save program space, control flow, and reduce unneeded repetition. But next time you write a LOOP AT statement, consider that with ABAP 7.40 and above you can reduce repetition even further!
Well, OK. Let me temper your expectations. Before you assume that there’s some magic secret MAKE_LOOPS_BETTER = abap_true compiler directive, know that what I’ll show you can reduce code by one line per LOOP. But don’t knock it: that can add up.
Use inline declarations for both DATA and FIELD-SYMBOLS statements whenever possible. Don’t clutter your programs with giant blocks of:
DATA: ls_mara TYPE mara.
*Repeat umpteen times for other DATA needed
FIELD-SYMBOLS: <ls_vbap> TYPE vbap.
*Repeat umpteen times for other FIELD-SYMBOLS needed
*Finally getting to:
LOOP AT it_mara INTO ls_mara.
do_stuff( ls_mara ).
ENDLOOP.
*and:
LOOP AT it_vbap ASSIGNING <ls_vbap>.
do_stuff( <ls_vbap> ).
ENDLOOP.
Instead, you can shorthand it like this:
LOOP AT it_mara INTO DATA(ls_mara).
do_stuff( ls_mara ).
ENDLOOP.
LOOP AT it_vbap ASSIGNING FIELD-SYMBOL(<ls_vbap>).
do_stuff( ls_vbap ).
ENDLOOP.
It may seem trivial. What took 8 lines of code now takes 6. Big deal, Paul. But consider when 80 lines of code reduced to 60, or 800 reduce to 600. Those giant DATA: … blocks are now smaller, and you spend less time mentally processing how data is allocated and more time processing how the program flows.
The other bonus: you’re less likely to want to risk the entire space-time continuum just to eliminate your past self for the verbose code.
View our LinkedIn, here.