I find myself frequently writing code that follows the following sequence:
- Attempt to open an I/O based resource (i.e. from a database and/or file). This could potentially fail.
- If successful, perform a series of operations via the object.
- These operations change based on user input. For example: filter data, do calculation A, do calculation B, write the results somewhere.
- Each of these operations could potentially fail and return with an error message. If a failure occurs at any time, the sequence should abort.
- Some operations must be done before others: writing results cannot occur before calculations, for example.
- Close the resource.
Is there a design pattern that would work well for a flow like this? When I try to wrap the above sequence into a class, the immediate problems I always run into are:
- How do deal with opening the resource. Ideally I would like to open it during class construction, but that gets messy if there is an error. Otherwise, I have to pass in a reference to the resource in the constructor, followed by an
Open()
method. - How to make the flow of operations flexible to a user of the object, but not burdening them with the need remember to call a bunch of intermediate methods and/or a lot of error checking.
Aucun commentaire:
Enregistrer un commentaire