Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design Pattern for a multi-step algorithm

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?

like image 851
disasterkid Avatar asked Oct 31 '13 14:10

disasterkid


4 Answers

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.

like image 96
CesarGon Avatar answered Oct 22 '22 00:10

CesarGon


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.

like image 27
Tim Hong Avatar answered Oct 22 '22 00:10

Tim Hong


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

like image 3
Menelaos Vergis Avatar answered Oct 21 '22 23:10

Menelaos Vergis


You can use either:

  1. Chain Of Responsibility. OR
  2. Maintain a List of Processes and loop through them to process your task. OR
  3. Use Function composition and chain your functions. In java 8 you can achieve this using Java 8 functional interfaces.

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.

like image 1
Bikas Katwal Avatar answered Oct 22 '22 00:10

Bikas Katwal