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

Immutable attributes – part 2

In part one of this post, I described, how to build a class containing public read-only attributes so we can imitate the FINAL attribute concept of JAVA.

Applying this in my daily development work, I came to a slight modification of this approach that uses one class per attribute. To keep the effort low, I use a template (in eclipse ADT) to quickly create such classes.

The immutable one-attribute class

My immutable class now looks like this:

class example_for_string definition.
  public section.
    data value type string read-only.
    methods constructor 
      importing value type string.

class example_for_string implementation.

  method constructor.
    me->value = value.


In incorporate this in the local definitions of my class. Then I create a private attribute

data example_for_string type ref to example_for_string.

In the constructor (or a different method that is used to initialize the attribute), I instantiate the object with the value, that usually is an import parameter and has the same name. Depending on personal preferences, one would eventually choose to use a prefix for the importing par

me->example_for_string = new #( example_for_string ).
* alternative:
example_for_string = new #( i_example_for_string ).

To speed up the work flow, I created this template in eclipse:

class ${name} definition.
  public section.
    data value type ${type} read-only.
    methods constructor 
      importing value type ${type}.
* to local implementations

  METHOD constructor.
    me->value = value.

* to class attributes
data ${name} type ref to ${name}.
* to implementation
me->${name} = new #( ${name} ).

I insert this template (where I have to give only the name and the type of my attribute) in the class-relevant declarations, then move the implementation to “local types” and the other two lines as indicated.

In the code, the immutable attribute can be accessed like this:

if example_for_string->value is initial.

Assigned Tags

      Be the first to leave a comment
      You must be Logged on to comment or reply to a post.