I have an outline for an algorithm - some logical steps that has to be performed in a specific order. The result of the algorithm has to be some number. Naturally this led me to the idea of using the template method pattern. This works fine for void
methods but here comes my problem: each of the steps in the algorithm is not a void
method but is allowed to return a number (so they are int
methods) - if a step returns a non-zero number, this number is the result of the algorithm's execution, if it is a zero - the execution continues with the next step.
This might sound really trivial but I just still find it somehow ugly to have something like:
public int algorithm() {
int resultStep1 = step1();
if (resultStep1!=0) {
return resultStep1;
}
int resultStep2 = step2();
if (resultStep2!=0) {
return resultStep2;
}
...
}
Of course step1()
, step2()
and so on are abstract methods and have their own specific implementations in the corresponding classes that extend mine.
The other idea that came to my mind was using exceptions but as we are talking about control flow here this would be an anti-pattern.
Am I missing something here or is this just the way I have to write it?
You can do the following:
Where: