Tuesday, 20 October 2015

Using Monads to manage exception handling

Lately I have been playing around with functional programming and F# and I have been trying to apply functional programming to C# as well. Even though C# is not a pure functional programming language, by supporting delegates, lambda method syntax and extension methods, we can produce code written in a functional style without any problems.

But I will not go into the details of explaining functional programing paradigm, but rather I will concentrate on how by using a specific functional structure called monad we can remove a lot of boilerplate code.

We all have seen a code like this:

Example 1:
    public void AddStudentToSchool(Guid schoolId, StudentDto studentDto)
    {
        using (ITransaction transaction = _transactionFactory.Create())
        {
            _securityService.Validate();

            School school = _schoolRepository.GetSchoolById(schoolId);
            if(school == null)
            {
                throw new ResourceNotFoundException("School does not exist");
            }

            try
            {
                Student student = new Student(studentDto);
                school.AddStudent(student);
            }
            catch(BusinessRuleException ex)
            {
                throw new ValidationException(ex.BrokenRules);
            }
            catch(InvalidStudentException ex)
            {
                throw new ValidationException(ex.BrokenRules);
            }
        }
    }


Wouldn’t it be more expressive and easier to read and understand the intention if we could write the following instead:

Example 2:
public void AddStudentToSchool(Guid schoolId, StudentDto studentDto)
{
    using (ITransaction transaction = _transactionFactory.Create())
    {
        _securityService.Validate();

        School school = _schoolRepository.GetSchoolById(schoolId);

        school.IfNullThrowResourceNotFound("School does not exist")
                .IfNotNull(() =>
                    {
                        Student student = new Student(studentDto);
                        school.AddStudent(student);
                    })
                .OnException<BusinessRuleException>(ex => throw new ValidationException(ex.BrokenRules))
                .OnException<InvalidStudentException>(ex => throw new ValidationException(ex.BrokenRules));
    }
}
Well, with the help of extension methods and by borrowing a structure from functional programming called monad we can.

Wikipedia defines the monad as following:

“In functional programming, a monad is a structure that represents computations defined as sequences of steps: a type with a monad structure defines what it means to chain operations, or nest functions of that type together. This allows the programmer to build pipelines that process data in steps, in which each action is decorated with additional processing rules provided by the monad.”

From the following paragraph, we are interested in the sentence “…This allows the programmer to build pipelines that process data in steps …” which is exactly what we want to achieve.

I won’t go into the details of explaining monads, but in essence a monad is a pattern for doing function composition with ‘amplified’ types (as Mike Hadlow puts it very eloquently on his blog series about monads). 

Going back to our code in example 1, if we study the code in essence what we trying to do is:

1.      Get the school from the repository
2.      If school is null throw an exception
3.      If school is not null then
4.      Try to execute more code (by adding the student to the school)
5.      If an exception is thrown, wrap that exception into ValidationException

To convert the above steps in chain of actions we need to make sure that the output of the previous action will be the input of the next action on the chain. So maybe monad (also known as Option in F#) will be adequate.

Before we dive in with writing code, let’s look at what do we need to implement for our type to be monad. Definition in the Wikipedia states the following:

For a type to be regarded a monad, it needs to have a type constructor M and two operations, bind and return:

·        The return operation takes a value from a plain type and puts it into a monadic container using the constructor, creating a monadic value.

·        The bind operation takes as its arguments a monadic value and a function from a plain type to a monadic value, and returns a new monadic value.

Maybe monad is very similar to Nullable<T> type in C#, except our maybe type will be represented by two different types. The Some type which will indicate a presence of a value and None type which will indicate an absence of a value. We will implement our maybe type as an interface and will call it IOptional. So the implementation looks like:

public interface IOptional<T>
{
}


The None type is implemented as :

public class None<T> : IOptional<T>
{
    public override string ToString()
    {
        return "None";
    }
}

And Some type is implemented as:

public class Some<T> : IOptional<T>
{
    public Some(T value)
    {
        Value = value;
    }

    public T Value { get; private set; }

    public override string ToString()
    {
        return Value.ToString();
    }
}

Now, to convert our IOptional<T> into a monad we need to implement the Return and Bind methods. We will be implementing them as extension methods. So the implementation looks like:

public static class OptionalExtensions
{
    public static IOptional<T> ToOptional<T>(this T value) where T : class
    {
        if (value == null)
        {
            return new None<T>();
        }

        return new Some<T>(value);
    }

    public static IOptional<T2> Bind<T1, T2>(this IOptional<T1> a, Func<T1, IOptional<T2>> func)
    {
        var val = a as Some<T1>;

        return val != null
            ? func(val.Value)
            : new None<T2>();
    }
}

Now our IOptional<T> type is monad. The next step is to start building the methods that we call chain them together. All the methods will be implemented as extension methods also.

The first one is throw if null. So the implementation looks like:

public static IOptional<T> IfNullThrowResourceNotFound<T>(this IOptional<T> value, string message)
    where T : class           
{
    Some<T> some = value as Some<T>;
    if (some == null)
    {
        throw new ResourceNotFoundException(message);
    }

    return value;
}


The next implementation is to try and execute an action if the value is not null. So the implementation looks like:

public static IOptional<Action> IfNotNull<T>(this IOptional<T> value, Action action)
    where T : class
{
    return value.Bind(t => new Some<Action>(action));
}



Next we will implement OnException step. The implementation looks like:

public static IOptional<Action> OnException<E>(this IOptional<Action> value, Action<E> action)
    where E : Exception
{
    return value.Bind(t =>
    {
        return new Some<Action>(() =>
        {
            try
            {
                t();
            }
            catch (E ex)
            {
                action(ex);
            }
        });
    });
}


And the last step is the Execute, which executes the code

public static void Execute(this IOptional<Action> value)
{
    value.Bind(t =>
    {
        t();
        return new None<bool>();
    });
}


Once we have finished implementing the extension methods, our code from example 1 looks like:

School school = _schoolRepository.GetSchoolById(schoolId);

school
    .ToOptional()
    .IfNullThrowResourceNotFound("School does not exist")
    .IfNotNull(() =>
        {
            Student student = new Student(studentDto);
            school.AddStudent(student);
        })
    .OnException<BusinessRuleException>(ex => { throw new ValidationException(ex.BrokenRules); })
    .OnException<InvalidStudentException>(ex => { throw new ValidationException(ex.BrokenRules); })
    .Execute();

As you can see, now our code looks a lot neater and easier to read without any boilerplate code. I hope you find this useful.


Friday, 24 April 2015

Build Where clause dynamically in LINQ

Imagine a scenario in which we have a collection of objects and want to allow the user to filter the collection by filtering on combination of properties. To make the scenario concrete, let's assume that our object is declared as follows:


public class Person
{
    public string Name { get; set; }
    public string Surname { get; set; }
    public int Age { get; set; }
    public string City { get; set; }
    public double Salary { get; set; }
    public bool IsHomeOwner { get; set; }
}

Now suppose we have a collection of Persons like this (this is just for explanation purposes, in real life you would get a much bigger collection from database):


List<Person> persons = new List<Person>
{
    new  Person  { Name = "Flamur" , Surname = "Dauti" ,    Age = 39,
                    City = "Prishtine" , IsHomeOwner = true ,  Salary = 12000.0 },
 
    new  Person  { Name = "Blerta" , Surname = "Frasheri" , Age = 25,
                    City = "Mitrovice" , IsHomeOwner = false , Salary = 9000.0 },
 
    new  Person  { Name = "Berat" ,  Surname = "Dajti" ,    Age = 45,
                    City = "Peje" ,      IsHomeOwner = true ,  Salary = 10000.0 },
 
    new  Person  { Name = "Laura" ,  Surname = "Morina" ,   Age = 23,
                    City = "Mitrovice" , IsHomeOwner = true ,  Salary = 25000.0 },
 
    new  Person  { Name = "Olti" ,   Surname = "Kodra" ,    Age = 19,
                    City = "Prishtine" , IsHomeOwner = false , Salary = 8000.0 },
 
    new  Person  { Name = "Xhenis" , Surname = "Berisha" ,  Age = 26,
                    City = "Gjakove" ,   IsHomeOwner = false , Salary = 7000.0 },
 
    new  Person  { Name = "Fatos" ,  Surname = "Gashi" ,    Age = 32,
                    City = "Peje" ,      IsHomeOwner = true ,  Salary = 6000.0 },
 
};

Suppose we want to allow the user to filter the collection on any property or any combination of properties (on our UI form). One way would be to have a function for each property and each combination of properties, something like:


public IList<Person> FilterByName(string name)
{
    return persons.Where(p => p.Name == name).ToList();
}
 
public IList<Person> FilterBySurname(string surname)
{
    return persons.Where(p => p.Surname == surname).ToList();
}
 
public IList<Person> FilterByNameAndSurname(string name, string surname)
{
    return persons.Where(p => p.Name == name && p.Surname == surname).ToList();
}

. . .


As you can see, this becomes a very tedious job since the number of functions to cover all possible combinations is quite big.

The other way to filter the collection, which is much more convenient and tidier is to build an expression tree dynamically and pass it to the where clause for filtering. The function signature that will build expression trees will look like:


public Func<Person, bool> Build(IList<Filter> filters)
{
    return null;
}

where Filter class is declared as:


public class Filter
{
    public string Property { get; set; }
    public object Value { get; set; }
}

And it is used to contain the name of the property and the value that we want to filter our collection on. I won’t go into the details of how to build expression trees, since there is a lot of information about it on the web, so the class for building the expression trees looks like:


public class PersonExpressionBuilder
{
    public static Func<Person, bool> Build(IList<Filter> filters)
    {
        ParameterExpression param = Expression.Parameter(typeof(Person), "t");
        Expression exp = null;
 
        if (filters.Count == 1)
            exp = GetExpression(param, filters[0]);
        else if (filters.Count == 2)
            exp = GetExpression(param, filters[0], filters[1]);
        else
        {
            while (filters.Count > 0)
            {
                var f1 = filters[0];
                var f2 = filters[1];
 
                if (exp == null)
                    exp = GetExpression(param, filters[0], filters[1]);
                else
                    exp = Expression.AndAlso(exp, GetExpression(param, filters[0], filters[1]));
 
                filters.Remove(f1);
                filters.Remove(f2);
 
                if (filters.Count == 1)
                {
                    exp = Expression.AndAlso(exp, GetExpression(param, filters[0]));
                    filters.RemoveAt(0);
                }
            }
        }
 
        return Expression.Lambda<Func<Person, bool>>(exp, param).Compile();
    }
 
    private static Expression GetExpression(ParameterExpression param, Filter filter)
    {
        MemberExpression member = Expression.Property(param, filter.PropertyName);
        ConstantExpression constant = Expression.Constant(filter.Value);
        return Expression.Equal(member, constant);
    }
 
    private static BinaryExpression GetExpression
    (ParameterExpression param, Filter filter1, Filter filter2)
    {
        Expression bin1 = GetExpression(param, filter1);
        Expression bin2 = GetExpression(param, filter2);
 
        return Expression.AndAlso(bin1, bin2);
    }
}


To test our expression builder, we would use it inside a method as follows:


List<Filter> filter = new List<Filter>
{
    new  Filter  { PropertyName = "City" , Value = "Mitrovice"  },
    new  Filter  { PropertyName = "IsHomeOwner" , Value = false  }
};
 
var deleg = PersonExpressionBuilder.Build(filter);
var filteredCollection = persons.Where(deleg).ToList();

As it is, the expression builder builds expression trees that check only if the value of the property is equal to the provided value, but we can take this approach one step further and make it generic so it can be used in other places with other types as well and also extend it so it can check for other comparisons as well. So our generic expression builder class will look like:


public static class ExpressionBuilder
{
    private static MethodInfo containsMethod = typeof(string).GetMethod("Contains");
    private static MethodInfo startsWithMethod =
    typeof(string).GetMethod("StartsWith", new Type[] { typeof(string) });
    private static MethodInfo endsWithMethod =
    typeof(string).GetMethod("EndsWith", new Type[] { typeof(string) });
 
 
    public static Expression<Func<T,bool>> GetExpression<T>(IList<Filter> filters)
    {
        if (filters.Count == 0)
            return null;
 
        ParameterExpression param = Expression.Parameter(typeof(T), "t");
        Expression exp = null;
 
        if (filters.Count == 1)
            exp = GetExpression<T>(param, filters[0]);
        else if (filters.Count == 2)
            exp = GetExpression<T>(param, filters[0], filters[1]);
        else
        {
            while (filters.Count > 0)
            {
                var f1 = filters[0];
                var f2 = filters[1];
 
                if (exp == null)
                    exp = GetExpression<T>(param, filters[0], filters[1]);
                else
                    exp = Expression.AndAlso(exp, GetExpression<T>(param, filters[0], filters[1]));
 
                filters.Remove(f1);
                filters.Remove(f2);
 
                if (filters.Count == 1)
                {
                    exp = Expression.AndAlso(exp, GetExpression<T>(param, filters[0]));
                    filters.RemoveAt(0);
                }
            }
        }
 
        return Expression.Lambda<Func<T, bool>>(exp, param);
    }
 
    private static Expression GetExpression<T>(ParameterExpression param, Filter filter)
    {
        MemberExpression member = Expression.Property(param, filter.PropertyName);
        ConstantExpression constant = Expression.Constant(filter.Value);
 
        switch (filter.Operation)
        {
            case Op.Equals:
                return Expression.Equal(member, constant);
 
            case Op.GreaterThan:
                return Expression.GreaterThan(member, constant);
 
            case Op.GreaterThanOrEqual:
                return Expression.GreaterThanOrEqual(member, constant);
 
            case Op.LessThan:
                return Expression.LessThan(member, constant);
 
            case Op.LessThanOrEqual:
                return Expression.LessThanOrEqual(member, constant);
 
            case Op.Contains:
                return Expression.Call(member, containsMethod, constant);
 
            case Op.StartsWith:
                return Expression.Call(member, startsWithMethod, constant);
 
            case Op.EndsWith:
                return Expression.Call(member, endsWithMethod, constant);
        }
 
        return null;
    }
 
    private static BinaryExpression GetExpression<T>
    (ParameterExpression param, Filter filter1, Filter filter2)
    {
        Expression bin1 = GetExpression<T>(param, filter1);
        Expression bin2 = GetExpression<T>(param, filter2);
 
        return Expression.AndAlso(bin1, bin2);
    }
}


And the filter class has been extended to take a comparison operation as well:


public class Filter
{
    public string PropertyName { get; set; }
    public Op Operation { get; set; }
    public object Value { get; set; }
}


And the operation is declared as enumeration:


public enum Op
{
    Equals,
    GreaterThan,
    LessThan,
    GreaterThanOrEqual,
    LessThanOrEqual,
    Contains,
    StartsWith,
    EndsWith
}


Then the new generic expression builder would be used as follows:


List<Filter> filter = new List<Filter>()
{
    new Filter { PropertyName = "City" ,
        Operation = Op .Equals, Value = "Mitrovice"  },
    new Filter { PropertyName = "Name" ,
        Operation = Op .StartsWith, Value = "L"  },
    new Filter { PropertyName = "Salary" ,
        Operation = Op .GreaterThan, Value = 9000.0 }
};
 
var deleg = ExpressionBuilder.GetExpression<Person>(filter).Compile();
var filteredCollection = persons.Where(deleg).ToList();


he ExpressionBuilder class can be extended for other Linq operations. It can also be easily used to remotely execute Linq statements (by making the class Filter serializable, it can be passed to a WCF service and so on). The most important thing to remember when adding features is that the expression generates a C# executable code. So for example if your property is Nullable<int> then you need to remember that Nullable<int> is a different type from int, and more importantly it does NOT implement all the properties/methods that int does, or if the property is string then the operations <, > and >= might return unexpected results.