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: 

Instantiation of class only when required parameters are present

Former Member
0 Kudos

Hi,

I have a class which has user id as import parameter for the constructor. My class is instantiated based on the USER ID and populates the attributes PERNR, NAME and POSITON.

Now when the constructor method is executed my class gets instantiated in all the scenarios. When i dont pass an user id all my parameters are blank but my class still creates an instance. But i want my instance to be created only when a valid user id is passed.

I tried to exit the constructor when an invalid user id is passed but still my class gets instantiated (with all attributes blank). One way could be i could check for the validity of the user id before instantiating my class but i want my constructor to take care of this.

Is this possible? Can someone let me know how to achieve this?

Thanks,

Prasath N

1 ACCEPTED SOLUTION

franois_henrotte
Active Contributor
0 Kudos

you should create a global method FACTORY that will handle the creation of objects

then in your program, you don't use CREATE OBJECT but in place

my_new_object_ref = ZCL_MY_CLASS=>FACTORY( parameters ).

This method FACTORY will do the CREATE OBJECT only if required parameters are present

Then if you want to be sure the object is always insatnciated using the factory, you change attribute of class "instanciation" to "private" so that noone can create an object from outside the class

3 REPLIES 3

franois_henrotte
Active Contributor
0 Kudos

you should create a global method FACTORY that will handle the creation of objects

then in your program, you don't use CREATE OBJECT but in place

my_new_object_ref = ZCL_MY_CLASS=>FACTORY( parameters ).

This method FACTORY will do the CREATE OBJECT only if required parameters are present

Then if you want to be sure the object is always insatnciated using the factory, you change attribute of class "instanciation" to "private" so that noone can create an object from outside the class

uwe_schieferstein
Active Contributor
0 Kudos

Hello Prasanth

You need to raise an exception if the USER ID is not valid, e.g.:

METHOD constructor. 
" IMPORTING parameter id_userid

" Check user id e.g. with BAPI_USER_EXISTENCE_CHECK and evaluate RETURN parameter
  IF ( ls_return-type CA 'AEX' ).
    MESSAGE 'User does not exist' TYPE 'E'
    RAISING not_exists.
  ENDIF.

...

ENDMETHOD.

Either you define an exception or an exception class in the CONSTRUCTOR signature.

Regards

Uwe

Former Member
0 Kudos

Hi,

This is easy. You may mark the parameter of the constructor as not optional. Check the parameter of the constructor. You will get the answer?

Regards,

Saurabh