Damian
Damian

Reputation: 3050

How to assure that methods will be executed in proper order?

I have always problem to design a class where proper method invocation would be clear to programmer, and there will be no danger of executing some method before data, variables are set by other method. So I usually use flags and If statements to be safe:

class foo {
    boolean isInitialised = FALSE;
    boolean isSthDone = FALSE;
    float importantData;

    public void initialise {

        ...

        isInitialised = TRUE;
    }

    public void doSth1 { 

      if (isInitialised) {

         importantData = 2134234; 

         }   ...

          isSthDone = TRUE;

    }

    public void doSth2 { 

        if (isInitialised && isSthDone1) {

            ...

          }
    }
}

This kind of design does not give any clue, how the algorithm should be used - which method should be executed first, is there any Design Pattern for this problem?

Upvotes: 3

Views: 1940

Answers (4)

dantuch
dantuch

Reputation: 9283

You should consider using State here. For me your code looks like:

  • "I'm in state that lets me initialise only"
  • "I'm in initialized state, so I can do needed logic - Sth1"
  • Lastly: "I'm in the last state so I can do now Sth2

http://sourcemaking.com/design_patterns/state

Anyway, like you were told before, the easiest option is to make those methods private and call them all in good order from one new public method.

Upvotes: 2

David
David

Reputation: 2620

You should be doing needed initialization in the constructor - that initialization is exactly what a constructor is for. Depending on the language you are using, it might look like this:

Class foo{

  public: 
  foo(){
    a = 1;
    b = "something";
  }

   int a;
   string b;

}

Upvotes: 6

TrueWill
TrueWill

Reputation: 25523

@D. Lambert and @David are giving good advice.

If you want a design pattern that enforces a sequence of calls, look at Template Method. That's probably not what you want here, and I have regretted choosing that pattern in the past, so use it with care. It enforces an order whether you like it or not.

Upvotes: 4

D. Lambert
D. Lambert

Reputation: 1304

Give some thought to whether independent execution of those steps really makes sense at all. If the consumer of that class really has to execute step 1, step 2, and step 3 in exactly that order, then just collapse them into one public method and encapsulate the steps within your class.

If, on the other hand, there really are options in terms of what the consumer does in which order, then you've got a state-transition problem, and you need to understand the legal sequences of steps.

Upvotes: 8

Related Questions