Reputation: 3050
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
Reputation: 9283
You should consider using State here. For me your code looks like:
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
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
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
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