The other day I was looking through some code and thought of a way to refactor the code using generics. I decided to create an example with the code in its current form and then see if I could make it work more generically. All the source can be found here (https://github.com/devdaves/genericconditions) on GitHub.
Here is the code example prior to using generics:
The method accepts a request object and returns a response object. There are several conditions that need to be validated prior to doing the work. All condition and do work methods check the status property in the response prior to doing any work. This way if Condition1 fails the rest of the methods will still be executed but the work will not be done since the status of the response is checked in each method.
What I am trying to solve is not running the other conditions or do work if the response status is in a faulted state. Now I know I could just add some conditions into this method but what's the fun in that. So time to refactor.
First the response needs to inherit from an IResponse that enforces that all responses will have a status property. This will come in handy when we create the generic method a little later in the post.
Next rewrite the Validate method with generics. Note the list of actions.
Initially the list of actions was sent to a method in the same class (DoToDo now commented out) and later turned into an extension method. This is the extension method.
This extension method will work off any list of actions that inherit from the IResponse interface created earlier. It will loop through the actions and execute each one and check the status. If the status is in a faulted state it will stop processing the list of actions. Since this is now generic any method we create in the project that uses the request/response pattern should be able to use this extension method to execute the conditions and dowork.
The cool thing here is not only are we short circuiting the process but each condition and dowork method no longer needs to check the status since its done in one place. If the logic that checks the status is done in only one place the maintenance of the code is much easier.
I have to admit that I haven't spent a lot of time playing with generics like this but I can see from a maintenance point of view that it can save some substantial time in a decent sized project. Plus I really like the way it reads although it does take some time to get used to.