How to assure that the methods will be executed in the correct order?

I always have a problem with creating a class in which the programmer would understand the correct call to the method and there would be no danger for the data to execute any method, and the variables are set by another method. Therefore, 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 type of design does not give any clue how to use the algorithm - which method should be performed first, is there a design pattern for this problem?

+3
source share
4 answers

Here you must use State . For me, your code is as follows:

  • " , "
  • " , - Sth1"
  • : " , Sth2

http://sourcemaking.com/design_patterns/state

, , - .

+2

, . 1, 2 3 , .

, , , , , .

+8

- - , . , , :

Class foo{

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

   int a;
   string b;

}
+6

@D. @ .

If you need a design pattern that provides a sequence of calls, check out the Template Method . This is probably not what you want here, and I regretted choosing this template in the past, so use it with caution. It provides order, whether you like it or not.

+4
source

All Articles