I'm writing a console application that goes through an algorithm with N number of steps. It is important that step N
is correctly done before step N+1
is executed. Otherwise the program should stop working with an error message.
I can do this with nested if
statements of course and use try-catch-finally
(using a continue flag in finally to decided if the program should process). But I am looking for a better structured design pattern or approach to do this. Any recommendations?
The Pipeline design pattern is precisely about this: carrying out a complex process in a strict sequence of steps. Google "pipeline design pattern" and you'll find plenty of resources.
This is a programming-oriented introductory article on MSDN, and this is a more theoretical post.
Chain of responsibility
http://www.codeproject.com/Articles/455228/Design-Patterns-3-of-3-Behavioral-Design-Patterns#Chain
or State pattern
http://www.codeproject.com/Articles/455228/Design-Patterns-3-of-3-Behavioral-Design-Patterns#State
may be the solutions of your problem.
For chain of responsibility pattern, when you detect error, you just need set the "error message (handling)" process as the next process in the chain.
For state pattern, you need to change the state to "Error" when encountering error, and handle all the errors in the error state.
Hopefully, that helps.
I have once created an process that was controlling an automation and I used an enumeration with all the steps
enum AutomationStep{Requested, Started, Waiting, Processing, Terminating};
Later I created a switch/case to process every step differently
switch (currentStep)
{
case AutomationStep.Requested : InitializeProcess(); currentstep = AutomationStep.Started; break;
case AutomationStep.Started : StartTheEngines(); currentstep = AutomationStep.Waiting; break;
case AutomationStep.Waiting : //etc
break;
default:
}
You may later use a While to run every step
You can use either:
One example from Java 8 APIs could be the use of a comparator interface.
Below is an example of chaining functions using function composition:
Comparator.comparing(name).thenComparing(age).
Click here for a detailed article on this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With