Application Development Discussions
Join the discussions or start your own on all things application development, including tools and APIs, programming models, and keeping your skills sharp.
cancel
Showing results for 
Search instead for 
Did you mean: 

Best Practice for using CAST operator

SuhaSaha
Advisor
Advisor
0 Kudos

Hello SDNers,

I looked up the SAP documentation but could not find any best practice on using the CAST operator multiple times in a procedure.

Approach#1:

          INSERT LINES OF:

            CAST child( parent )->table1 INTO TABLE ex_table1,

            CAST child( parent )->table2 INTO TABLE ex_table2.

Approach#2:

         

          DATA(child) = CAST child( parent ).

          INSERT LINES OF:

            child->table1 INTO TABLE ex_table1,

            child->table2 INTO TABLE ex_table2.

In the former i am casting twice, whereas in the latter i am using a helper variable.


SAP documentation states & i quote,


The casting operator CAST is suitable for avoiding the declaration of helper variables needed only for down casts.

If i consider this statement as the thumb-rule, then approach#1 is better.

What do you think?

BR,

Suhas

6 REPLIES 6

matt
Active Contributor
0 Kudos

I'd tend to 1) but always consider readability.

0 Kudos

Matthew Billingham wrote:

... but always consider readability.

Hence the question

Former Member
0 Kudos

I would vote for 2) in this special case because of the readability.

But maybe one should think about a different solution. If I would need a cast twice or more, I would think about splitting up the logic into several blocks. In OO-words: I would split up the one method which uses the cast more times into two methods. Whereby the called method contains the coding with the casts, which would be resolved by using a parameter with the already correct interface/class to use and the calling method then has to do a single cast.

I have some more ideas to resolve the nasty casting, but I won't blow up the post.

0 Kudos
I would split up the one method which uses the cast more times into two methods.

Hi Armin,

Thanks for the response!

Unfortunately i cannot split the method because it is a callback-routine of an aRFC.

The solution is not an elegant one, but unfortunately i don't have the leisure of refactoring the stuff.

BR,

Suhas

0 Kudos

Is it not possible to call another method inside the callback-routine?

Another idea is: Provide two methods at your "child" class, which append the corresponding content. To avoid the redundant casting you can use chaining (returning the object itself, i.e. ME):


CAST child( parent )->append_tab1_to( CHANGING ct_table = ex_table1 )->append_tab2_to( CHANGING ct_table = ex_table2 ).

0 Kudos
Is it not possible to call another method inside the callback-routine?

As i have mentioned, i don't have the flexibility of refactoring the code now. Maybe in the next sprint