Skip to Content
Technical Articles
Author's profile photo Jörg Krause

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!

Motivation

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.

Approach

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.

Assigned Tags

      5 Comments
      You must be Logged on to comment or reply to a post.
      Author's profile photo Matthew Billingham
      Matthew Billingham

      Very elegant!

       

      Author's profile photo Oleg Bashkatov
      Oleg Bashkatov

      Very good! Thank you for sharing!

      Could you use that (or something similar) for reference variables?

      Author's profile photo Jörg Krause
      Jörg Krause
      Blog Post Author

      The reference itself would remain immutable, but the value it points on not... what kind of use-case are you thinking of?

      Author's profile photo Rainer Lindemann
      Rainer Lindemann

      Lovely - this one goes straight into my mental toolbox for future use.

      Author's profile photo Christian Guenter
      Christian Guenter

      Nice!

      FYI SAP introduced FINAL to ABAP with Netweaver 789 which is going into a similar direction (but doesn't work for attributes). It's already available in in the cloud and was spoilered here.