OO Design Pattern Decorator – Why do we need to use helper variable?

By | December 11, 2011 | ABAP Objects, OO Design Patterns | 6,283 | 0

Recently, we have seen how we can achieve OO Design Pattern Decorator in ABAP using the inheritance tree. Achieving decorator seems to be little bit complex, but it gets easier as we get used with it.

Problem

As you can notice, in this example that we had to use the helper variable LO_PRE to retain the object reference of the previous instantiated object.

Decorator using Helper

 

DATA: lo_decorator TYPE REF TO output,
lo_pre TYPE REF TO output. ” Helper Variable

* Setup objects
* standarad object
CREATE OBJECT lo_decorator TYPE alvoutput.
lo_pre = lo_decorator.

* testing Decorator
IF iv_pdf IS NOT INITIAL.
CREATE OBJECT lo_decorator TYPE op_pdf
EXPORTING
io_decorator = lo_pre.
lo_pre = lo_decorator. ” << ENDIF. IF iv_email IS NOT INITIAL. CREATE OBJECT lo_decorator TYPE op_email EXPORTING io_decorator = lo_pre. lo_pre = lo_decorator. " << ENDIF. [/abap_code] If we don't use the helper variable and do the code like this - it seems fine - but it goes to endless loop. [abap_code slider="X" title="Without using Helper variable"] CREATE OBJECT: lo_decorator TYPE alvoutput lo_decorator TYPE op_pdf EXPORTING io_decorator = lo_decorator, lo_decorator TYPE op_emain EXPORTING io_decorator = lo_decorator. [/abap_code]

Why this happens

The endless loop is the result of the usage of LO_DECORATOR. Because when system executes this statement it carries the new object created in the IO_DECORATOR parameter. So, the object has the reference of its OWN object instead of the SUPER object. This happens because as soon as system executes the statement CREATE OBJECT it creates the object before calling the constructor. SO, when it reaches to constructor it has its OWN object reference instead of the SUPER object reference.

This is what SAP Help point out to:

The CREATE OBJECT statement creates an instance of a class or object and assigns the object reference to the reference variable oref. Directly after the object has been created, the instance constructor of the class is executed.

Original forum discussion can be found on SDN at Design Pattern, The decorator

Further Reading

Explore all other Design patterns. More are comming soon.

Tags

Like It? Share!!

Don't miss an Update

Get notified of the new post, right into your inbox

Naimesh Patel{274 articles}

I'm SAP ABAP Consultant for more than a decade. I like to experiment with ABAP especially OO. I have been SDN Top Contributor.
Follow :

Explore all of his 274 articles.

Load comments

Comments on this Post are now closed. If you have something important to share, you can always contact me.

You seem to be new here. Subscribe to stay connected.