ABAP OO requires in its object oriented programming style the assignment of the methods and attributes to the class section (a.k.a. access modifiers) private, protected and public (explained for Java). This programming language is often enhanced at customer projects to accommodate customer specific requirements. Hence, the usage of those access modifier in the standard coding is having a considerable impact on the time those customer enhancements need to be implemented as well as the time they need to be maintained.
I have noticed that the access modifiers private or protected are used in several cases where a less restrictive access modifier would have kept the possibility to reuse more standard coding and reduced the required additional custom code. Therefore, I will provide 5 rules of thumb and hope to start a discussion leading to a more relaxed use of the access modifiers.
- If no subclass exists, never use it!
- If in question, use protected instead.
- Private methods do only make sense if they access private attributes.
- Access modifier of choice if other classes should be prevented from changing the attribute directly or calling the method.
- Access modifier of choice if other classes cannot do any harm by or should be allowed to change the attribute directly or call the method.
Following those rules will provide also guidance on how to encapsulate coding even when no subclass exists at the moment. For example, modifying private attributes should be done in a private method most of the time.
If you wonder why this is important? Let’s look at the following example:
None of the attributes should be private:
The first three attributes start with the prefix ‘GC_’ and are private constants. The naming convention states that the first letter ‘G’ is used to indicate the global usage of this constant, so already at that point it is obvious that there is something wrong with the access modifier being private. Another hint would be rule 1. and the fact that this class has no subclass. Furthermore, since the nature of constants is that they cannot be modified access cannot do any harm so rule 5. applies and those attributes should be public.
The last attribute IO_TOR_SRVMGR is an attribute that is initialized in the redefined method FILL_PRINTSTRUCTURE and the other methods only use read access to that attribute. This also indicates that the usage of the access modifier private is too restrictive. I would suggest to use protected instead especially when thinking about possible subclasses. This change would enable them to also use the read access when redefining one of the other methods.