Home > dotnet 4, Dotnet 4.5 > Refactoring with LINQ

Refactoring with LINQ

In this post I am going to talk about a simple refactoring technique using LINQ and I hope it will give you some insight into the power of LINQ.

Recently I came across with a very specific requirement where as soon as we persist our aggregate root (Code First POCO) into the database, the entire object need to be stored in an audit table as a key value pair (property and values).

I know it may sound a bit strange but hey requirements are requirements and if it adds value to the business then why not.

I thought it would be easy as I can use JavaScript Serialzer and store it as a JSON object in SQL Server database but that was not the case as the requirement specifically said it has to be just a key value pair.

Also the JavaScript Serializer solution would not have worked as I had one-to-many and then many-to-many relations in EF Code first POCO objects and JavaScript Serializer was giving exception due to circular objects.I could have tried fixing the seriliazer problem but I didn’t pursue it too hard as this technique was not a fool-proof solution.

So I googled it and found this reflection helper class

ReflectionHelper.cs

 public static class ReflectionHelper
{
    public static string DisplayObjectProperties(Object o)
    {
        StringBuilder sb = new StringBuilder();
        System.Type type = o.GetType();
        foreach (PropertyInfo p in type.GetProperties())
        {
            if (p.CanRead)
            {
                object obj = p.GetValue(o, null);
                if (obj != null)
                {
                    sb.AppendLine(String.Concat("-Property name: ", p.Name ));
                    sb.AppendLine(String.Concat("-Property value:", obj.ToString()));
                    sb.AppendLine();
                }
                else sb.Append(String.Concat(p.Name, " # Value is null"));

            }
        }
        return sb.ToString();
    }
}

The code is pretty slick and does what it is supposed to do and worked in my scenario, no problem at all.

I then decided how can I make this code even better and leverage some of the new language feature. For me foreach loop with lots of if else conditions is a code smell and had to do something about it. So here is the refactored code using LINQ.

ReflectionHelper.cs

public static class ReflectionHelper
{
    public static string DisplayObjectProperties(this Object o)
    {
        var sb = new StringBuilder();
        var type = o.GetType();
        var query = from property in type.GetProperties()
                    where property.CanRead &&
                          property.GetValue(o, null) != null
                    select property;

        foreach (var propertyInfo in query)
        {
            sb.AppendFormat("{0}:{1}\n", propertyInfo.Name,
                                propertyInfo.GetValue(o));
        }
        return sb.ToString();
    }
}

As you can see nothing fancy but all the ifs conditions have been converted into a LINQ query,a simple technique but looks good.

Happy Clean Coding !!! 🙂

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: