0% found this document useful (0 votes)
31 views4 pages

Static vs Instance Methods in ABAP

Static methods in ABAP can be called directly without instantiating an object but have several disadvantages compared to instance methods. Static methods cannot be redefined via polymorphism, make unit testing more difficult because they use static attributes, and do not allow reusing utility logic in the same session without losing data. Instance methods are preferable because they allow polymorphism via redefinition, easier testing by clearing object attributes between tests, and allow multiple instances to operate independently in the same session. Static methods should mainly be used for object creation patterns like factories rather than helper classes.

Uploaded by

Nikhil Malpe
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views4 pages

Static vs Instance Methods in ABAP

Static methods in ABAP can be called directly without instantiating an object but have several disadvantages compared to instance methods. Static methods cannot be redefined via polymorphism, make unit testing more difficult because they use static attributes, and do not allow reusing utility logic in the same session without losing data. Instance methods are preferable because they allow polymorphism via redefinition, easier testing by clearing object attributes between tests, and allow multiple instances to operate independently in the same session. Static methods should mainly be used for object creation patterns like factories rather than helper classes.

Uploaded by

Nikhil Malpe
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Static Methods

Static methods are methods which can be called irrespective to the class instance. You
can access only static attributes and static events within the Static method.

This is how you declare and call static method:

 
* static method declaration
CLASS lcl_data DEFINITION.
PUBLIC SECTION.
CLASS-METHODS:
get_data IMPORTING iv_date TYPE d.
ENDCLASS. "lcl_data DEFINITION
*
* static method call - calling using class name
lcl_data=>get_data( '20130313' ).
*
CLASS lcl_data IMPLEMENTATION.
METHOD get_data.
* do something
ENDMETHOD. "get_Data
ENDCLASS. "lcl_data IMPLEMENTATION
 

Instance Methods

Instance methods are methods which can be ONLY called using the object reference.
Instance methods can access instance attributes and instance events.

This is how you declared and call instance method:

 
*Instance method declaration
CLASS lcl_data DEFINITION.
PUBLIC SECTION.
METHODS:
get_data IMPORTING iv_date TYPE d.
ENDCLASS. "lcl_data DEFINITION
*
* Instance method call - calling using the object reference
DATA: lo_data TYPE REF TO lcl_data.
CREATE OBJECT lo_data.
lo_data->get_data( '20130313' ).
*
CLASS lcl_data IMPLEMENTATION.
METHOD get_data.
" get data
ENDMETHOD. "get_data
ENDCLASS. "lcl_data IMPLEMENTATION
 
Why not to use Static methods
As you can see from the sample code, It may sound good and lucrative to create a static
method as it does not involve long steps when calling the methods – declaring reference
variable, instantiating the object and calling method. Static method can be directly called
without doing these steps. But the design using static will not be as good as it sounds.
Let me show you why:

Static methods cannot be Redefined


One of the most important aspect of the Object Oriented programming is the
Polymorphism – replacing the default implementation with the more specific
implementation whenever its required. In OO ABAP the polymorphism would be
achieved using Method Redefinition. As we have discussed in earlier article Override
Static method, we can’t redefine Static methods. The primary reason behind this is static
methods are operable on their own. With static methods, you call them by explicitly
specifying the type on which they are defined. Which means, you directly call the
implementation, which is not bound to any specific implementation of the instance
object.

Lets see this by the a simple scenario – If you have static method which does the Sales
Order Creation using the BAPI. When you designed, this method was only used for one
business scenario. Now, you want to use this for different business scenario. In this new
scenario, you need to set some additional fields on item, like Higher Level item,
determine a new item category etc. What you would think as a simple solution would be
to add a code block in the method to do this logic for XYZ Sales Area, ZABC order type.
What you have done here is opened a box where you would keep on adding more and
more conditions. Thus violating the Single Responsibility Principle.

If you had an Instance method, you could have easily inherited another class, redefined
the method and replaced the existing implementation. In this new implementation, you
set the additional fields and call Super Method to do the rest.

Problem in ABAP unit testing


I haven’t covered ABAP Unit yet. They are coming soon…

Test Fixture

In ABAP unit, you can set the test data in special methods called test fixtures. After this
method, your test method would be called where you have access to test data. Since
each ABAP Unit test should be operable and testable on its own, Static methods makes
it very difficult to test with. Static methods would use static attributes and since they are
using that, you have to have additional logic to get rid of them all the time in your test
fixture methods.
If you are working with the instance if the object, it can be easily cleared. When you
instantiate a new object, the old object would be de-referenced without any additional
logic

Constructor

Design using the static methods would end up using the CLASS_CONSTRUCTOR, as
opposed to the method CONSTRUCTOR for Instance methods. As I noted
earlier, CLASS_CONSTRUCTOR and CONSTRUCTOR: Who comes before whom?, it
would be difficult to predict when CLASS_CONSTRUCTOR would be called.
CLASS_CONSTRUCTOR can be called when the class is first accessed even though it
was accessed to get Constant value. This makes it inoperable and un-testable on its
own.

Reuse the Utility in same Session


Static attributes would be bound to memory till the session is over. This means that if the
values are set once, they wont be cleared until the session is finished. If static attributes
it won’t be possible to leverage the same logic in the same session. E.g. A simple utility
class to generating Application Log.

The design is like:

 Collect log in an attribute of the static class


 Call static method to generate Application log after the collect.

The design seems fully appropriate for the utility class which should be static. But the
problem with this is, it restrict you from using the same logic again in the same session
without losing the existing information. Lets say, you are collecting a errors using this
application log. Now, in the same program, you wont to generate another application log
to track the activities performed. Since you have collecting all the errors in the static
attributes, unless you copy it into another placeholder and call the Utility class for
generating the tracking log, you would lose the error log data when you try to use the
same Utility class.

On the other hand, you had a design using instance method and attributes, you would
be able to simply create another instance and start using it for tracking log.

Thumb Rules
So based on all these facts, we can conclude to these thumb rules:

 If you are planning to create any static attribute which would be used by static
method, Consider creating instance methods. It would allow you to work with
multiple instances. It also allows you to control on when you can free up the
bound memory.
 If you think that there would be a chance to add a conditional logic in future, Go
for instance. This makes design more flexible by allowing you to leverage
polymorphism by Redefinition
 Static should only used for object creation design patterns like Singleton, Factory
Method, Abstract Factory, Singleton Factory to facilitate the object creation.
 Static should be for pure utility classes not for helper classes. The best examples
would be methods within the class CL_GUI_FRONTEND_SERVICES.

Common questions

Powered by AI

Static methods have several drawbacks, especially in ABAP. They cannot be redefined due to their inherent design, which limits polymorphic behavior such as method redefinition—key for adaptable implementations in different scenarios . This limitation can lead to codebases that violate the Single Responsibility Principle by accumulating conditions and logic within a single method. Additionally, static methods complicate unit testing as they rely on static attributes which are hard to clear within test setups . These challenges make the use of static methods less flexible compared to instance methods, particularly when future adjustments or testing are anticipated.

Static methods and their attributes bind memory until the session's end, which can restrict reuse within the same session and complicate memory management . This is problematic when static methods are involved in unit testing because they inherently possess persistence characteristics that require additional logic to manage . In contrast, instance methods facilitate easier memory management as they allow new instances to be created without lingering state and can be separately dereferenced, simplifying the testing process by avoiding conflicts related to shared state .

When conditional logic is expected to evolve, instance methods are preferable as they support method redefinition, allowing enhanced flexibility and maintaining adherence to the Single Responsibility Principle . This design enables the addition of new functionalities and adjustments to be accommodated within subclass redefinitions, preventing the main method from becoming unwieldy with multiple conditional branches .

Static methods do not participate in polymorphism as they cannot be redefined or overridden, which limits their ability to adapt or extend specific functionalities provided by the class . Polymorphism relies on method overriding to dynamically alter behaviors in subclasses, a key feature for flexible and reusable code. The static nature of these methods mars this flexibility, restricting their utility in dynamic application contexts where different object behaviors are advantageous .

The decision to use static versus instance methods should consider factors such as memory management, future conditional logic, and testability. Instance methods are advisable when anticipating conditional logic evolution, as they accommodate method redefinition . They also support better memory management by allowing multiple instances and easier testing due to non-persistent state across class instances . Static methods should be reserved for scenarios where class-level actions are necessary, such as design patterns that benefit from singular management. Thus, aligning method choice with anticipated complexity and use cases helps maintain a clean and flexible design .

The CLASS_CONSTRUCTOR in static methods presents issues of unpredictability because it can be invoked the first time a class is accessed, even for simple operations like retrieving a constant . This unpredictability complicates operability and can lead to unintended behavior especially when the timing of class static resource initialization impacts application logic or testing results. Unlike standard constructors in instance methods, which provide more predictable and controllable initialization with each object instantiation, CLASS_CONSTRUCTOR lacks deterministic invocation patterns .

In ABAP Unit testing, static methods pose challenges due to their reliance on static attributes, which must be managed explicitly within test fixtures to avoid state retention issues across tests . Conversely, instance methods are more naturally suited for unit testing; each test case can create its own instance, ensuring clean setup and teardown procedures that avoid shared state complications . This encapsulation supports isolated testing environments where object state can be tightly controlled, producing more reliable and maintainable tests .

Instance methods are more aligned with the Single Responsibility Principle as they allow each method to be focused and limit its functionality, supporting more manageable code units . The ability to use redefinition ensures that each method has a single, clear responsibility that can be altered without branching logic within the same block of code. Static methods, by contrast, often centralize functionality, requiring embedded conditions to handle various scenarios. This design contradicts the Single Responsibility Principle by merging multiple responsibilities into a single method, increasing complexity and maintenance burdens .

Static methods are most appropriately used in scenarios involving object creation design patterns like Singleton or Factory Method patterns, as well as in pure utility classes such as those within CL_GUI_FRONTEND_SERVICES . These patterns benefit from a centralized method of instantiation or utility functionality, where the advantages of direct class access outweigh the downsides of inflexibility or testing difficulty .

Static attributes persist in memory for the entire session duration, which hinders their reuse within the same session for different logs or utility tasks. For instance, once a log is generated using static methods, attempting to generate another log within the same session could result in data loss from the initial log unless additional handling logic is employed . This persistence can complicate management when the application logic requires multiple distinct uses of similar functionalities in the same session, as opposed to instance methods that easily manage separate states .

You might also like