Sunday, November 4, 2012

Messing around with Generics

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:

public ExampleResponse ValidateExampleWithoutGenerics(ExampleRequest request)
{
    ExampleResponse response = new ExampleResponse();

    Condition1(request, ref response);
    Condition2(request, ref response);
    Condition3(request, ref response);
    //could be many conditions...
    DoWork(request, ref response);

    return response;
}

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.

public interface IResponse
{
    Status Status { get; set; }
}

Next rewrite the Validate method with generics.  Note the list of actions.

public ExampleResponse ValidateExampleWithGenerics(ExampleRequest request)
{
    ExampleResponse response = new ExampleResponse();

    List<Action<ExampleResponse>> todo = new List<Action<ExampleResponse>>()
    {
        {(r) => {Condition4(request, ref r);} },
        {(r) => {Condition5(request, ref r);} },
        {(r) => {Condition6(request, ref r);} },
        {(r) => {DoWork2(request, ref r);} },
    };

    //DoToDo<ExampleResponse>(todo, ref response);
    todo.RunWithShortCircuit(ref response);

    return response;
}

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.

public static void RunWithShortCircuit<T>(this List<Action<T>> actions, ref T response)
    where T : IResponse
{
    foreach (var action in actions)
    {
        if (response.Status.StatusCode == 0)
        {
            action.Invoke(response);
        }
        else
        {
            // short circuits the rest of the actions from running
            break;
        }
    }
}

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.

3 comments:

  1. My C# is a little rusty, but I don't think you need the ref keyword, since the response is not a value type it should pass by reference automatically. Cool trick!

    ReplyDelete
    Replies
    1. Yeah the ref keyword is not required in this instance. The original code I was refactoring had the ref keyword included so it was more explicit on what was happening. Thanks for commenting though.

      Delete
  2. This comment has been removed by the author.

    ReplyDelete