I have a .NET console app which calls several methods and I want to be sure that I call them in the correct order. More precisely I want that the code doesn’t compile if the order is not correct. For example
If I change to this
It still compiles but it doesn’t work necessarily.
We’re going to leverage the OOP paradigm to force the execution order. The idea is very simple each method will take as input a “result object” from the previous method.
We should also avoid situations like
All the code is available at the execution order repo
In order to give some context I’m going to pretend that the console app has 3 methods:
We’re moving each method to a separate class, first of all Init which has no “dependency” on the other methods, it should be the first one we call.
Since Init has a private constructor we could not create it from anywhere outside the class itself. Now in the Work class the “Execute” method is gonna ask for an instance of the Init class, this way we have to call Init.Execute first.
Private constructor, same reason as before. Argument validation in order to avoid passing null to the Work.Execute method. Last of all the Close class which needs a Work instance but doesn’t return anything since it’s last one to call.
The solution is not perfect because it depends on the Argument validation in order to work.
Our program now is ugly but we have to follow the correct order.