Tag Archive for c#

Generating generic delegates with expression trees

A few weeks ago I was working in a patch for an awesome mocking meta framework named mfakes, a very awesome mocking meta-framework based in the spicy Machine Specification BDD testing framework, go, try it, you are going to love it!.

Well, one of the awesome points in mfakes it’s to abstract mocking frameworks, so mfakes provides adapters for popular mocking frameworks like Rhino Mocks, Moq, NSubstitute and FakeItEasy. So instead of thinking which one to use, just concentrate in the test. Simple.

Anyway, there was a feature lacking in mfakes, and as every developer when something it’s lacking a feature you just go ahead and implement it, nothing beats open source. The interesting point was trying to “wrap” different way to interact between every mocking framework, everyone has a different way to see the world, it’s not bad, but it’s different. I found a very interesting problem with FakeItEasy and constructor parameters in a Mock.

In most mocking frameworks there’s an easy way to specify constructor parameters for a mock, in Moq, for example, you just do something like this:

var foo = new Mock<T>("foo", "bar");

// Generate this it's easy, it's just a simple generic type
// with a parameter list

public object CreateFake(Type interfaceType, params object[] args) {
    var closedMockType = typeof(Mock<>).MakeGenericType(interfaceType);
    var objectProperty = closedMockType.GetProperty("Object", closedMockType);
    var instance = (args != null && args.Length > 0)
        ? Activator.CreateInstance(closedMockType, args) : Activator.CreateInstance(closedMockType);
    return objectProperty.GetValue(instance, null);
}

The problem it’s that FakeItEasy it’s magic, and uses a very nice strong typed way to do it

var foo = A.Fake<FooClass>(x =>
    x.WithArgumentsForConstructor(
        new[] object {"foo", "bar"}));
// Another way to do it, more strongly-typed
var foo = A.Fake<FooClass>(x =>
    x.WithArgumentsForConstructor(
        ()=> new FooClass("foo", "bar")));

Well, if you think about that, there’s not a simple way to abstract a non-generic, non-typed expression with a generic, strong-typed, functional expression, well, not a simple way to do it at least you use the expressiveness of binary expression trees. How do we abstract this? well, let’s see the simple expression:

Now, let’s create a function to return that expression based in parameters, let’s abstract everything with the only knowlege of the type and the parameters:

// Transforming this:
var foo = A.Fake<T>(Action<IFakeOptionsBuilder<T>> opts)

// Implies something like this
public static Delegate CreateForType(Type type, object[] args) {
    var optType = typeof(IFakeOptionsBuilder<>).MakeGenericType(new[] { type });
    var actType = typeof(Action<>).MakeGenericType(new[] { optType });

// Now we have the type for the action and the options builder
// Let's use it to create an expression tree!

    var r = Expression.Parameter(optType, "r");
    var method = optType.GetMethod("WithArgumentsForConstructor", new[] { typeof(IEnumerable<object>) });
    var p = Expression.Constant(ctorArgs);
    var call = Expression.Call(r, method, p);
    var lambda = Expression.Lambda(actType, call, new[] { r });
    var exp = lambda.Compile();
}

And well, now that we have the function to call (we generated it), it’s time to create the fake

public object CreateFake(Type type, params object[] args) {
    var closedFakeType = typeof(Fake<>).MakeGenericType(interfaceType);
    var objectProperty = closedFakeType.GetProperty("FakedObject", interfaceType);

    var options = args != null && args.Length > 0
        ? FakeItEasyHelper.CreateForType(interfaceType, args) : null;

    var instance = args != null && args.Length > 0
        ? Activator.CreateInstance(closedFakeType, new object[] {options})
        : Activator.CreateInstance(closedFakeType);

    return objectProperty.GetValue(instance, null);
}

See? that’s the reason because Functional programming it’s so awesome, functions are just another variable, you can generate them, use them, modify them, use them. Next time you have a problem try to think in a functional way, you will see how awesome is!.

More about Expression Trees in the amazing book C# in Depth, Second Edition by John Skeet or go and pick a functional language (like this Programming F#), study it, enjoy it, use it in your favourite non-functional language.

Happy coding!

NOTE: the patch it’s already included in mfakes, no worries!

Haskell, C# y Currying

Aunque el concepto de “Currying” no es algo extraño para los lenguajes funcionales (y por lo tanto bastante conocido entre usuarios de este tipo de lenguajes). No es sólo una palabra extraña sino un concepto quizás desconocido para muchos usuarios de lenguajes imperativos como C#.

Currying (llamado así en nombre de Haskell Curry) no es más que el efecto de tomar de forma individual parámetro por parámetro y procesar cada parámetro por separado en su propia función, esto lo logramos tranformando el método o función en cuestión por uno que tome uno de los parámetros y una función para luego retornar otra función. Por ejemplo, tomemos el hecho de una simple suma:

sum       :: (Int, Int) -> Int
sum (x, y) = x + y

En este caso indicamos una función llamada sum que toma dos parámetros de tipo Int y retorna un parámetro de tipo Int. Dado que las funciones son ciudadanos de primer orden en los lenguajes funcionales, podemos transformarla y definir una función que tome como uno de sus parámetros una función y retorne otra función

sum'     :: Int -> Int -> Int
sum' x y = x + y

En este caso, creamos la función sum’ que toma un parámetro tipo Int y retorna otra función que toma un parámetro tipo Int y retorna un Int. Si, ya se que a simple vista esto puede parecer extraño, pero regresemos a ver un par de puntos claves: Currying involucra evaluar uno a uno los parámetros de una función pudiendo retornar otra función en su lugar.

Bien, regresemos a la Tierra y veamos como podemos transformar este tipo de cosas en una forma más "C#". Aprovechando los métodos lambda en C# (otra adición netamente funcional) podemos describir algo como esto:

public static void Main()
{
    Func<int, int, int> sum =
        (x, y) => x + y;

    int result = sum(1,2);

    Console.WriteLine(result);
}

Pero que les parecería si cambiamos "un poco" la definición de la función sum:

public static void Main()
{
    Func<int, Func<int, int>> sum =
        x => y => x + y;

    int result = sum(1)(2);
    Console.WriteLine(result);
}

Ahora sum en vez de tomar dos enteros como parámetro y retornar un entero, ahora toma un entero retorna una función (que toma un entero y retorna otro entero) como parámetros. De esta manera sum(1) retornará otra función que luego toma el parámetro 2 y retorna 3, wow…

El concepto de currying es práctico, permite definir funciones complejas a partir de funciones mucho más simples, aunque la definición en C# parece compleja, en realidad permite definir una función a partir de simplemente un parámetro (el cual convenientemente puede permanecer dentro de la función como si fuera una constante).

public static void Main()
{
    Func<int, Func<int, int>> ntimes =
        x => y => x * y;

    var twice = ntimes(2);
    var three = ntimes(3);

    Console.WriteLine(twice(4));
    Console.WriteLine(three(4));
}

Es interesante todo lo que podríamos lograr con solamente un poco de imaginación. :)

C# y el caracter Wildcard de Haskell

Escuchando al Dr. Meijer en su serie Functional Programming with Haskell, me topé con algo interesante: el caracter wildcard de Haskell. El "wildcard” (_) en Haskell es prácticamente lo mismo que el caracter wildcard (*) en nuestros sistemas operativos, evalúa o implica cualquier “otra cosa”. Por ejemplo:

(&&)         :: Bool -> Bool -> Bool
True && True = True
_ && _       = False

Tiene una interpretación sumamente sencilla: “Dada una función llamada &&, que toma un Bool y retorna una función que toma un Bool y retorna un Bool siendo sus parámetros True y True retornará True, de cualquier otra manera, retornará False”. A simple vista pensaremos que en lenguajes de “diario” no existen conceptos como el de “wildcard”, pero como lo dice luego el Dr. Meijer, en C# si tenemos el concepto de wildcard, claro, con nuestros amigos los Generics (otro concepto tomado de lenguajes funcionales y que data de muchos años atrás :P ).

En C# el guión bajo es un nombre aceptado de una variable, así que podemos utilizarlo como caracter de wildcard (a lo Haskell), imaginemos la declaración desiguiente tipo genérico:

public interface IRepository<T> {
    T GetById(int id);
}

Bien, que tal si lo nombramos algo así:

public interface IRepository<_> {
    _ GetById(int id);
}

Debo admitir que en mi caso lo veo algo extraño para los tipos de retorno… Que tal si usamos un wildcard para aquellos tipos que "debemos" definir pero que no "vamos" a utilizar.

// Siendo esta la declaración de un evento
runtime.RuntimeStarted += (sender, e) => Console.WriteLine(e.InstanceId);

// De igual manera, sender es un Object el cual no utilizamos
runtime.RuntimeStarted += (_, e) => Console.WriteLine(e.InstanceId);

Si, ya se que más de algún usuario de VB.NET me comentará que en VB9 no es necesario declarar en los eventos aquellos parámetros que no utilizaremos, pero esa es harina de otro costal.

Al parecer si hay un par de cosas que un usuario de C# puede aprender de Haskell… Saludos!

The complex way is not really the right way…

Today I was visiting a client, and I just stop and watch something that really caught my attention:

foreach (item in myList) {
    if (item.Length > 0) {
        SaveItem(item);
    }
}
// more ugly code...

Well, the code was really different (an uglier one) but you got the idea…. What I suggested to my client was a more concise solutio, create an extension method:

public static class IEnumerableExt {
    public static IEnumerable<T> ForEach(this IEnumerable<T> items, Action<T> action) {
        foreach(var item in items) {
            action(e);
        }
    }
}

The second part is the easy one…

myList
    .Where((item) => item.Length > 0)
    .ForEach((item) => SaveItem(Item));

I don’t know you, but this way looks a lot clearer to me…

Lessson learned: If your code looks complex, please, take a time and look how to make it more clearer.

Calculando la edad con un método de extensión

Algo que es bien recurrente y hasta “básico” en muchas de nuestras aplicaciones es el cálculo de la edad para una fecha dada. Tomando esto en cuenta y aprovechando a nuestros amigos los métodos de extensión me cree un par de métodos sencillos que pueden más de algún día salvarnos un par de minutos.

using System;
using Xunit;
using Xunit.Extensions;

namespace Rioshu.Educa.Facts
{
    public class DateTimeExtensionFacts
    {
        [Fact]
        public void Can_calculate_age_with_simple_dates()
        {
            var past_date = DateTime.Now.AddYears(-10);
            Assert.Equal(10, past_date.Age());
        }

        [Fact, FreezeClock(2009, 01, 01)]
        public void Can_calculate_age_with_not_so_simple_dates()
        {
            var past_date = new DateTime(2002, 02, 13);

            Assert.Equal(7, past_date.Age());
        }

        [Fact]
        public void Can_calculate_age_with_a_base_date()
        {
            var from_date = new DateTime(2010, 01, 01);
            var past_date = new DateTime(2002, 02, 13);

            Assert.Equal(8, past_date.Age(from_date));
        }
    }
}

Y aquí la implementación del helper

    public static class DateTimeExtensions
    {
        public static int Age(this DateTime date)
        {
            return Age(date, DateTime.Now);
        }

        public static int Age(this DateTime date, DateTime from_date)
        {
            if (from_date.Month <= date.Month && from_date.Day < date.Day) {
                return from_date.Year - date.Year - 1;
            }

            return from_date.Year - date.Year;
        }
    }

Como siempre acepto sugerencias y comentarios :) Hasta la próxima!