Search code examples
design-patternspseudocode

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?


Solution

  • 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.