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.
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.
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.
mv_my_attribute = ABAP_TRUE
SET_MY_ATTRIBUTE( ABAP_TRUE )
IF mv_my_attribute = ABAP_TRUE
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?