A common sequence of steps we mortal software developers frequently find ourselves implementing goes something like this:
- Perform some sort of setup or acquire some sort of resource.
- Carry out some arbitrary sequence of actions.
- Tear down things we setup or release resources we acquired in step 1.
There are well-known patterns for implementing this scenario robustly, but when there are multiple sub-steps to be performed in the setup phase and where any of those sub-steps can each fail individually, things get more complicated. This article presents a concise, self-documenting and robust way to handle these more complicated cases. A follow-up article will extend this further to improve some performance characteristics and ends up having a lot in common with the ScopeGuard11
pattern described in various places online.
The multi-step setup problem
Conceptually, the problem we want to solve can be described as follows:
- For each setup sub-step:
- Perform sub-step.
- If sub-step fails, stop and release/clean up after all previous setup sub-steps.
- Carry out some arbitrary sequence of actions.
- Tear down things we setup or release resources we acquired in all sub-steps of step 1.