Quantcast
Viewing all articles
Browse latest Browse all 19

EdLib

Over the years as a developer, I’ve come to realise that I have encountered similar problems and have had to write same kind of code. I’m sure most of us would have gone through that kind of experience, when we wished we had saved the code snippet or functions in a central area so we can re-use it.

I’ve decided to do exactly that. I’ve created a personal library where I want to store useful, reusable code that helps me in my everyday work, and hopefully will be useful to others too. Coming up with a name was hard, so I’ve decide to concatenate my name and the work “Lib” together, which becomes EdLib.

For the first addition, I’ve decided to solve a common problem all of us would have encountered at some point. For instance, you have to access a property that’s nested, and you end up writing many ifs to check for null, like so

if (person != null)
{
    if (person.Membership != null)
    {
        if (person.Membership.Account != null)
        {
            return person.Membership.Account.AccountNumber;
        }
    }
}
return 0;

It sucks to have to write code like that, and would be great to be able to compress that into a single line, evaluate if the account number can be retrieved otherwise return 0.

I’ve used Expression to achieve that. I’ve added extension methods for getting and setting nested property values using Expressions.

public static bool TrySetValue<T, TResult>(this T instance, Expression<Func<T, TResult>> expression, TResult value) where T : class

public static void SetValue<T, TResult>(this T instance, Expression<Func<T, TResult>> expression, TResult value) where T : class

public static TResult GetValueOrDefault<T, TResult>(this T instance, Expression<Func<T, TResult>> expression) where T : class

public static TResult GetValue<T, TResult>(this T instance, Expression<Func<T, TResult>> expression) where T : class

GetValueOrDefault will evaluate the expression; if any of nested object references are null, the default value will be returned.
GetValue will evaluate the expression; if any of the nested object references are null, an exception will be thrown.
SetValue will set the value for the expression; if it cannot evaluate the expression, an exception will be thrown.
TrySetValue will set the value for the expression, if it cannot evaluate the expression, it returns false.

Usage of the GetValueOrDefault extension method would vastly simplify the nested if code snippet above, like so…

return person.GetValueOrDefault(x=>x.Membership.Account.AccountNumber);

You can get the source and unit tests for this @ Github.

Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 19

Trending Articles