dhernandez dhernandez - 1 year ago 79
C# Question

Want to enforce specific order of methods execution of a class, when this class is used. Does exist a design pattern for this?

I have a class that represents a process

internal class IntegrationWithSalesforce
public IntegrationWithSalesforce()
{ // Initialize internal variables }

public bool GetListOfCustomersToImport() { ... }
public bool CreateSalesforceJob() { ... }
public bool CreateJobBatches() { ... }
public bool CloseSalesforceJob() { ... }
public void UpdateBatchesProcessingInfo() { ... }
public bool AbortJob() { ... }

methods should be execute in specific order until you invoke CloseSalesforceJob.

I want to enforce this order of execution:
1- class initialization
2- call GetListOfCustomersToImport if true
3- call CreateSalesforceJob if true
4- call CreateJobBatches if true
5- call CloseSalesforceJob
6- then keeps calling UpdateBatchesProcessingInfo until all batches states
have value Completed ,Failed

My first idea is have boolean variables that represent state(or execution )
and set the one related with method to true when method is called, or throw custom Exception ProcessOrderExecutionException if method is not the next in order.

For example:

// add this variable to my class
bool processInitialized = false;
bool customerSumaryListRetrieved = false;
bool salesforceJobSuccessfullyCreated = false;
bool salesforceBatchesSuccessfullyCreated = false;

a) method GetListOfCustomersToImport implementation

public bool GetListOfCustomersToImport()
//at the end
customerSumaryListRetrieved = true;


b) method CreateSalesforceJob

public bool CreateSalesforceJob()
throw new ProcessOrderExecutionException();

//at the end
// method implementation
salesforceJobSuccessfullyCreated = true;

Is there a better way to do this? A design pattern, or a known implementation?

Answer Source

If that's the only acceptable way to perform the action, then write a method that does exactly that, and make that the only public method for your class. None of these other methods should be public if it's not acceptable for them to be called in any other way.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download