piątek, 11 września 2009

My virtual static implementation

What I want is to be able to write code like this:

public T Create<T>() where T : new(string)

{

    return new T("something");

}

or this:

public interface IConverter<Tin, Tout>

{

    static Tout Convert(Tin value);

}

 

public static Tout Convert<TConverter, Tin, Tout>(Tin value)

    where TConverter : IConverter<Tin, Tout>

{

    return TConverter.Convert(value);

}

but current (4.0) version of C#/CLR doesn’t allow me to do it, so I was forced to think about substitute solution.

If we think about virtual methods we need class that has them and we need instance of this class.

public class IntStringConverter : IConverter<int, string>

{

    public static readonly IntStringConverter Instance = new IntStringConverter();

    public virtual string Convert(int value)

    {

        return value.ToString();

    }

}

But this gives us nothing because we need to know exact type. So I’ve created following class

public static class Static<T> where T : new()

{

    private static bool initilized;

    private static T value;

 

    public static T Value

    {

        get

        {

            if (!initilized)

            {

                value = new T();

                initilized = true;

            }

            return value;

        }

    }

}

to use it instead of Instance field.

And now I can write Convert method like this:

public static Tout Convert<TConverter, Tin, Tout>(Tin value)

    where TConverter : IConverter<Tin, Tout>, new()

{

    return Static<TConverter>.Value.Convert(value);

}

or Create method

public interface INew<T, T1>

{

    T New(T1 param1);

}

 

public static T Create<T, TFactory>() where TFactory : INew<T, string>, new()

{

    return Static<TFactory>.Value.New("something");

}

So my solution is to create one instance of my “virtual static” type and make sure all other classes can use it without tight coupling to some static field. Right now, all they need to know is Static<T> class.

wtorek, 25 sierpnia 2009

Why should you use generics instead of simple interfaces in method parameters in .NET

Answer: for performance reasons

Consider following methods

public static void TestMax()

{

    int max = (int)Max(5, 10);

}

 

public static object Max(IComparable left, IComparable right)

{

    return left.CompareTo(right) > 0 ? left : right;

}

Now let see how TestMax() is looking when compiled to IL

.method public hidebysig static void TestMax() cil managed
{
.maxstack 2
.locals init ([0] int32 max)
L_0000: nop
L_0001: ldc.i4.5
L_0002: box int32
L_0007: ldc.i4.s 10
L_0009: box int32
L_000e: call object Test.Program::Max(class [mscorlib]System.IComparable, class [mscorlib]System.IComparable)
L_0013: unbox.any int32
L_0018: stloc.0
L_0019: ret
}


So as we can see for this simple call we have two box instructions. This means that we have two heap allocations (malloc() in c).


Now lets see how generic version will behave:




public static void TestMax()



{



    int max = Max(5, 10);



}



 



public static T Max<T>(T left, T right) where T : IComparable



{



    return left.CompareTo(right) > 0 ? left : right;



}




and TestMax() in IL looks like this:



.method public hidebysig static void TestMax() cil managed
{
.maxstack 2
.locals init (
[0] int32 max)
L_0000: nop
L_0001: ldc.i4.5
L_0002: ldc.i4.s 10
L_0004: call !!0 Test.Program::Max<int32>(!!0, !!0)
L_0009: stloc.0
L_000a: ret
}


As you can see instead of box we now have ldc instructions which means that now we are allocating 2*4 bytes on the stack which is much much faster then allocation on the heap.



So the long answer is: Because by this simple tweak you can speed up your method for all struct parameters.

piątek, 7 sierpnia 2009

How to test generic class/methods with Rhino mocks

Rhino mocks is my isolation framework of choice and as you my notice from my earlier post I use generics as my Inversion of Control tool. Problem is that when you use Rhino Mocks you cannot mock constructor (right now to my knowledge only TypeMock Isolator can do this). The reason for this is that Rhino Mocks generates mocks at runtime, and for testing methods that use new() constraint you need to know the mock type at compile time.
So the only way to solve this seems to be creation of mock classes by hand. But then shortly I realized that all of them seems to look very similar.
So…

Here is how I solved this:
First I created t4 file called Mocks.tt which I attach to my test project.

It’s almost unreadable, so don’t be scared – I’m not t4 expert, it’s my first experiment :-)

This file is:

  • generating MockAttribute class
  • searching for each class in project (it belongs to) that have such attribute and are partial and then creates mock methods for each interface this class implements and for default constructor.

To create such mock type I must first write something like this:

[Mock]

public partial class MockAskEmailWindow : IQuestion

{

}

Then click “Run Custom Tool”

run custom tool

And because IQuestion is defined like this

public interface IQuestion

{

    string Ask(string question);

}

in file generated by t4 script I have following code

public partial class MockAskEmailWindow

{

    private readonly MockAskEmailWindow mock;

    public bool Created;

    public MockAskEmailWindow Object;

 

    public MockAskEmailWindow()

    {

        if (Service<Queue<MockAskEmailWindow>>.Value != null)

        {

            mock = Service<Queue<MockAskEmailWindow>>.Value.Dequeue();

            mock.Created = true;

            mock.Object = this;

        }

    }

    public virtual string Ask( string question)

    {

        return mock.Ask( question);

    }

}

Now if we have following method to test:

public string AskForNewUserEmail<TQuestion>() where TQuestion : IQuestion, new()

{

    throw new NotSupportedException();

}

We write test like this:

[Test]

public void ShowUsermNewUserEmailRequestAndRetrieveEmail()

{

 

    var ask = MockRepository.GenerateMock<MockAskEmailWindow>();

 

    ask.Expect(a => a.Ask("Plase type email of the user you want to create")).Return("test@test.pl");

 

    using (Service.CreateQueue(ask))

        Assert.AreEqual("test@test.pl", AskForNewUserEmail<MockAskEmailWindow>());

    ask.VerifyAllExpectations();

}

And to make test pass we change our method to

public string AskForNewUserEmail<TQuestion>() where TQuestion : IQuestion, new()

{

    return new TQuestion().Ask("Plase type email of the user you want to create");

}

Seems, simple :-)
The only unknown class that I used here is Service<> so here is it’s very simple code

public class Service<T> : IDisposable where T : class

{

    private readonly T parent;

    [ThreadStatic] private static T current;

 

    public Service(T service)

    {

        parent = Value;

        Value = service;

    }

 

    public static T Value

    {

        get { return current;}

        private set {current = value;}

    }

 

    public void Dispose()

    {

        Value = parent;

    }

}

 

public static class Service

{

    public static Service<Queue<T>> CreateQueue<T>(T value, params T[] values)

    {

        var queue = new Queue<T>(values.Length + 1);

        queue.Enqueue(value);

        foreach (var v in values)

            queue.Enqueue(v);

        return new Service<Queue<T>>(queue);

    }

}

This class I created as my implementation of service locator earlier when I tried use this pattern to decouple the code. As you can see from code, service implementations can be nested and are specific for current thread (I failed to create services that work between multiple thread because of strange CallContext class behaviour when someone called EndInvoke()). If anyone is interested here is example of usage:

using (new Service<IQuestion>(new MockAskEmailWindow()))

{

    //some code

    using (new Service<IQuestion>(new MockAskEmailWindow()))

    {

        //some other code that uses other version of IQuestion

        //by calling Service<IQuestion>.Value

    }

    //here we use again the first IQuestion

}

But back to generic method testing as you can see from example above the scheme is following:

  • Create mocks using Rhino Mocks
  • put them in the service queue
  • run tested method
  • When mocked type instance is created it takes mock from service queue
  • All calls to newly created object are redirected to mock created in test

And that’s it.

Just one more note: Because of EnvDTE unavailability to read generic constraints (and because it was failing when I called CodeMethod.StartPoint and CodeMethod.EndPoint) I was unable to mock such methods. I solved this by don’t mocking it at all. You must implement such method in your part of partial mock class.

Hope this helps someone

czwartek, 30 lipca 2009

C# generics – free but ugly Dependency Injection

I must admit that: I’m obsessed with generics for some time.

 

Some time ago my way to decouple code was to use IServiceProvider. It was great but required from me and my coworkers to pass it to each newly created class.

In the mean time other developers used different IoC containers which solved this problem by using static methods to register and use specific objects. For example:

IOC.Register<ISomething>(new Something());

 

And later in the code it was used like this:

 

IOC.Resolve<ISomething>().DoSomething();

As I said it solved one problem but I had still other problems with that:

  • Because of static methods I can have only one configuration for the whole application
  • Even if I tried to create my version of IoC container that can be nested like this

    using(new Service<IService>(new ServiceImplementation()))

    {

        //some code

        //and later

        using(new Service<IService>(new AnotherServiceImplementation()))

        {

            //some other code

        }

    }


    I failed to create a version that worked correctly between multiple threads, because I was forced to use static fields and I was unable to force CallContext to not overwrite current Thread configuration when EndInvoke() was called.
  • If I want to write component that may be used by someone else the only way to inform him about required dependencies is documentation, or runtime errors.
  • I must agree with Joel Spolsky that code that uses IoC containers is less readable

Aside from above I’m using static language C#. Why should my dependencies be resolved at runtime. I had never written application that required dynamic dependencies. All of them was known to me while I was writing my applications. Why not use compiler as my dependency resolver.

So, I want to write decoupled and reusable methods and classes.  This can be achived partially by parameter or property Dependency Injection.

Great, but after a while you come to the moment when you must create new object that will be passed to this method or property.

What now, how can I create instance of class without coupling to concrete type, and not using IServiceProvider or static IoC Container (or worse: use reflection). Then it hit me: we can make new() constraint on generic type. That way I can write my method/class in a way that it will create instances without knowledge of concrete type. We can create really decoupled/reusable code using  generics.

 

After few tests I also created short rule:

Every time you must call new() – do it on generic type. (It doesn’t matter if it’s method or class scope generic type)

 

There is one problem with this rule – I must use default constructor - which means – I must inject all already instantiated dependencies by properties or method parameters.

Last month I had small project to create application to manage users in database where data are encrypted. It was separate, small exe file – so I thought that I test my thoughts about generics. As example of decoupled code lets see fragment of my UserCreator class:

public class UserCreator<TRepository, TCertificateStore, TCertificate, TUserLoginQuestion, TPasswordGenerator> : IUserCreator<TRepository>

    where TRepository : IRepository

    where TCertificateStore : ICertificateStore<TCertificate>, new()

    where TCertificate : ICertificate

    where TUserLoginQuestion : IQuestion, new()

    where TPasswordGenerator : IPasswordGenerator, new()

{

    public TRepository Repository { get; set; }

 

    public void CreateFirstUser()

    {

        var store = new TCertificateStore();

        var adminCert = store.CreateAdministratorCertificate();

        store.SaveAdministratorCertificate();

        var login = new TUserLoginQuestion().Ask();

        var userCert = store.CreateUserCertificate(login);

        store.SaveUserCertificate(userCert);

        var userCertBytes = userCert.ToBytes();

        Repository.CreateNewUser(login, userCert.Encrypt(Encoding.ASCII.GetBytes(new TPasswordGenerator().Generate())), userCertBytes);

        Repository.CreateNewAdministrator(userCertBytes, adminCert.Sign(userCertBytes));

    }

}

Uhh, little ugly – but (almost) completly decoupled (Encoding.ASCII.GetBytes is not important dependency in that case). To make this class more usable I created also default version

public class UserCreator : UserCreator<RepositoryDataContext, CertificateStore, Certificate, AskUserEmailForm, PasswordGenerator>{}

As you can see I can change everything this class uses to whatever implementation I want. What blows my mind is – how such small method requires so much dependencies. Below you have example of usage:

public static void Main<TRepository, TAdministratorTable, TAdministrator, TUserCreator, TLogin, TApplication>(TRepository repository)

    where TRepository : IRepository, IAdministratorRepository<TAdministratorTable, TAdministrator>

    where TAdministratorTable : IQueryable<TAdministrator>, ITable

    where TAdministrator : IAdministrator, new()

    where TUserCreator : IUserCreator<TRepository>, new()

    where TLogin : ILogin, new()

    where TApplication : IApplication, new()

{

    try

    {

        if (repository.Administrators.Count() == 0)

            new TUserCreator{Repository = repository}.CreateFirstUser();

        var login = new TLogin();

        login.Login();

        if (login.UserAuthenticated)

            new TApplication().Start();

    }

    catch(CancelException)

    {}

}

In line

            new TUserCreator{Repository = repository}.CreateFirstUser();

you can see that I must pass repository as property. It will be great if I can make a constraint for constructor other than default. For example

    where TUserCreator : IUserCreator<TRepository>, new(TRepository)

but right now I must live with a tools I have (c# 3.0). I don’t have strong opinion which is better default constructor + properties or specific constructor.

 

I was afraid that when my codebase will grow the list of dependencies will grow, especially in Main() method. What I observed instead of this was that each method require max 6-10 dependencies. Not so scary.

 

OK time for some summary:
Pros:

  • Completly decoupled/reusable code
  • Completly testable code
  • Best performance possible (no boxing for value types)
  • Free – you already have all tools – I mean you already have one tool – compiler :-)
  • All dependencies are resolved by compiler
  • User of your code knows all dependencies at compile time (using only intellisense)
  • Because dependencies are static, they will not change in other thread (until you say so)

Cons:

  • Little ugly method/class definition (I’m sure that better type inference would help here, but I’m not sure how much better is possible)
  • Only constraint for default constructor is possible
  • No possibility to use static methods (MS please add static virtual methods)

If anyone isintrested I’ll try to write in short time how I test such generic methods/classes. Especially how I test newly created instances. All I can say right now is that I use t4 script and Rhino Mocks.