Creating method dependency in java

I have two method names like sendSData () and sendCData () in MyClass.

class MyClass
{

       public void sendSData()
        {
          // Receiving Response from database
        }

        public void sendCData()
        {
         // send C Data
        }

}

      

I am calling these two methods from the main method

public static void main(String ... args)
{
    MyClass obj=new MyClass();
    obj.sendSData();
    obj.sendCData();
}

      

It is possible to send a sendCData request after and only if I received a response from the sendSData () method.

How can I achieve this in java?

sendData () post data to server, if I get a successful response from the server then I manage to send sendCData (). I am using a pub / submodule. I am not calling any web or REST service. I have a separate subscriber to receive an answer

+3


source to share


5 answers


public boolean sendSData() {
    // handle whether or not the function returns true or false
    return true;
}

public static void main(String ... args) {
    MyClass obj=new MyClass();

    if (obj.sendSData()) {
        obj.sendCData();
    } else {
        // obj.sendSData() did not successfully respond
    }
}

      



With the above code obj.sendCData()

will only execute if it sendSData()

returns true (answered successfully).

+1


source


You must explicitly check if it was sendSData

successful.



You can encapsulate this check in a new method, which after calls sendCData

or even check at the beginning for sendCData

and if it was not successful do nothing

0


source


You can try something like this:

class MyClass
{

 public static boolean setFlag = false;

       public void sendSData()
        {
          // Receiving Response from database
             setFlag = true;
        }

        public void sendCData()
        {
            if(setFlag==true)
            {
         // send C Data
            }
        }

}

      

Boolean view can help you to call sendCData correctly and check correctly if setFlag is correct.

0


source


You will most likely solve this problem after it has already been recommended (using a simple boolean flag). However, there may be another alternative. I think you can take advantage of the Inversion of Control (IoC) function. Even if this is not the best alternative for your case, or even if it is too much, I recommend you go through this tutorial if you can: http://www.springbyexample.org/examples/intro-to-ioc.html .

0


source


Throwing an exception from 'sendSData' on failure will also do the trick, it ensures that 'sendCData' is not called.

0


source







All Articles