Dirty assignment is a technique we all use sometimes. Imagine that the ABAP program ZPROG1 makes a call to ZCLASS=>METHOD1. If METHOD1 needs to access a global variable within ZPROG1, the following trick can be used:
ASSIGN ‘(ZPROG1)GV_SAMPLE’ TO . = 5.
This code will change the value of the global variable GV_SAMPLE within ZPROG1. Although this operation is highly insecure and may cause instabilities, it is a dire technique needed at times.
So far so good. It works fine on global variables. But what about local variables? What if your method needs to access a local variable; in a form, for instance? Check the following case:
REPORT zprog1. FORM form1. DATA lv_local TYPE i. lv_local = 5. ZCLASS=>METHOD1( ). ENDFORM.
Imagine that you need to access lv_local from within METHOD1. Assigning ‘(ZPROG1)LV_LOCAL’ doesn’t work because lv_local is not a global variable.
Well, here is the trick. Create an enhancement in FORM1 where you send the data reference of LV_LOCAL to ZCLASS.
REPORT zprog1. FORM form1. “””””””””” ENHANCEMENT FIELD-SYMBOLS TYPE i. ASSIGN (‘lv_local’) TO . ZCLASS=>SET_REF_OF_LV_LOCAL( iv_local_ref = REF#( ) ). “””””””””” DATA lv_local TYPE i. lv_local = 5. ZCLASS=>METHOD1( ). ENDFORM.
Please note that you can’t assign LV_LOCAL directly because at the point of enhancement, it is not defined yet. But you can assign it dynamically as (‘LV_LOCAL’).
The imaginary method ZCLASS=>SET_REF_OF_LV_LOCAL will store the reference somewhere within the class:
METHOD set_ref_of_lv_local. gr_local = iv_local_ref. ENDMETHOD.
At this point, ZCLASS=>METHOD1 can access the local variable easily.
METHOD method1. FIELD-SYMBOLS TYPE i. ASSIGN gr_local->* TO . ADD 1 TO . ENDMETHOD.