Application Development Blog Posts
Learn and share on deeper, cross technology development topics such as integration and connectivity, automation, cloud extensibility, developing at scale, and security.
cancel
Showing results for 
Search instead for 
Did you mean: 
k1000
Explorer
Declaring Class Attributes as PUBLIC READ-ONLY can be quite polarising. To some, it is bad practice to be avoided at all costs. To others, it’s a life-saver.

I can see the arguments for both sides, but cannot decide for myself.

Why use:

  • It saves you the work of declaring code-littering getters.

  • It enables accessing Objects in an internal table by their PUBLIC READ-ONLY Attributes, such as:


LOOP AT lt_objects WHERE mv_my_attribute
SORT lt_objects BY mv_my_attribute

This behaviour can be leveraged in a number of design patterns, e.g. in a Decorator.

 

Why avoid:

  • Having a dedicated getter is actually a Good Thing. Especially if you enforce accessing Class Attributes via their setters and getters even internally, within the Class itself. Then you can put a BREAK-POINT inside the getter / setter, and be sure it’ll stop every time anyone tries to access the Attribute. This is easier than chasing the Attribute down its where-used list.

  • This syntax doesn’t exist in other programming languages.

  • Eclipse generates the getters and setters for you automatically, so what’s the big deal anyway?


 

I have worked in an environment where PUBLIC READ-ONLY was considered bad practice, and never used. It was required that Class Attributes be accessed by their getters and setters always, even from within the Class.

No
mv_my_attribute = ABAP_TRUE

but rather
SET_MY_ATTRIBUTE( ABAP_TRUE )

 

No
IF mv_my_attribute = ABAP_TRUE

but rather
IF GET_MY_ATTRIBUTE( ) = ABAP_TRUE

 

The Architect was successful at enforcing this rule in code reviews. However, it cost him time and energy, especially when a new member of the team joined.

I would be keen to hear your opinions on the topic. Is PUBLIC READ-ONLY to be encouraged, or discouraged?

 
19 Comments