Approach for immutable attributes
In JAVA, we have FINAL for making sure, a variable is assigned only once. This blog is about how to emulate this concept with ABAP
After reading, have a look at part two of this blog!
Often, when I decide to extract a complex method into a new class, I struggle with the fact, that importing parameters should not change in the class.
Usually, I turn all the parameters into class attributes which makes the importing parameters changeable. My motivation was to avoid being able to change these attributes once they are set.
I use a little local class to keep all the immutable variables:
class read_only definition final. public section. data vbdkr type vbdkr read-only. data vbdpr type vbdpr read-only. data nast type nast read-only. methods constructor importing i_vbdkr type vbdkr i_vbdpr type vbdpr i_nast type nast. endclass. CLASS read_only IMPLEMENTATION. METHOD constructor. vbdkr = i_vbdkr. vbdpr = i_vbdpr. nast = i_nast. ENDMETHOD. ENDCLASS.
Since the public attributes are read-only, they can be only accessed with read.
In the entry method, I instantiate the class passing my importing variables:
read_only = new #( i_vbdkr = i_vbdkr i_vbdpr = i_vbdpr i_nast = i_nast ).
In the coding, I access the variables using the direct reference
ls_ftechdat-vbeln = read_only->vbdkr-vbeln. ls_ftechdat-posnr = read_only->vbdpr-posnr. ls_ftechdat-vgbel = read_only->vbdpr-vgbel.
Result: as soon as I try to change the values in the read_only class, I will get a syntax error.