Wednesday, December 31, 2008

I couldn't possibly say this any better...

Comment by LKM on http://www.codinghorror.com/blog/archives/001201.html:


About convenience:

Pirated media is not free to the pirate. He pays with his time. Now you can't compete with the price of time for people who don't work. To most teenagers, time is way less valuable than money. No matter how convenient you make buying your stuff, these people won't give you their money. However, that is not the case for people who have jobs. To people like us, even finding a working torrent file may not be worth the hassle if we can instead open the Amazon MP3 store, type the name of the song we want and click "buy".

In many cases, the price doesn't even enter the equation. To me, whether I have ten bucks more or less on my credit card statement at the end of the month simply doesn't matter at all. What matters is whether I spend ten minutes looking for a song, or ten seconds.

Ironically, DRM makes it *less* convenient to buy, thus giving potential customers more incentive to pirate.

About instant gratification:

If possible, allow users to download whatever you're selling. Don't make them wait for the Amazon package to arrive if you can avoid it. Give them a file they can download right after clicking "buy", and don't make them pay additionally for the privilege.

Tuesday, December 30, 2008

Repository pattern

[Edited on June 6, 2009.]

This is my implementation of the Repository pattern in C#; I am using the ServiceLocator defined in my previous post.

This is the main interface:

  1. public interface IRepository<TEntity, TId>  
  2.   where TEntity: IEntity<TId>  
  3. {  
  4.   /// <summary>  
  5.   /// Returns all entities in the repository  
  6.   /// </summary>  
  7.   /// <returns>List of entities</returns>  
  8.   IEnumerable<TEntity> GetAll();  
  9.   
  10.   /// <summary>  
  11.   /// Returns all entities matching a criteria  
  12.   /// </summary>  
  13.   /// <param name="criteria">Criteria to be matched</param>  
  14.   /// <returns>All entities matching the criteria; should not be null, but it can be an empty list</returns>  
  15.   IEnumerable<TEntity> FindAll(Expression<Func<TEntity, bool>> criteria);  
  16.   
  17.   /// <summary>  
  18.   /// Returns the first entity matching a criteria  
  19.   /// </summary>  
  20.   /// <param name="criteria">Criteria to be matched</param>  
  21.   /// <returns>The first entity that matches a criteria; can be null</returns>  
  22.   TEntity Find(Expression<Func<TEntity, bool>> criteria);  
  23.   
  24.   /// <summary>  
  25.   /// Finds a record with a given id  
  26.   /// </summary>  
  27.   /// <param name="id">Key to search</param>  
  28.   /// <returns>The record with the given id or null if none exists</returns>  
  29.   TEntity Find(TId id);  
  30. }  


Now, I am always creating a primary key for each table, and nowadays I call it Id. It's normally an autoincrementing integer, but for users or other sensitive information I will probably switch to GUIDs, so the type of the primary key should be a parameter. Here is the entity interface, representing a record in a table:

  1. namespace Helper  
  2. {  
  3.   public interface IEntity<TId>  
  4.   {  
  5.     TId Id { getset; }  
  6.   }  
  7. }  


As you can see, the only relevant thing is the primary key :)

I've extracted the updates to another repository... this is incompletely refined, you might need more granularity (some repositories might support updates but not deletes, for example).

  1. public interface IUpdateableRepository<TEntity, TId>  
  2.   where TEntity : IEntity<TId>  
  3. {  
  4.   /// <summary>  
  5.   /// Adds an entity to the repository; the repository may change the entity's Id on adding  
  6.   /// </summary>  
  7.   /// <param name="entity">Entity to add</param>  
  8.   void Add(TEntity entity);  
  9.   
  10.   /// <summary>  
  11.   /// Deletes an entity  
  12.   /// </summary>  
  13.   /// <param name="entity">Entity to delete</param>  
  14.   void Delete(TEntity entity);  
  15.   
  16.   /// <summary>  
  17.   /// Updates an entity  
  18.   /// </summary>  
  19.   /// <param name="entity">Entity to update</param>  
  20.   void Update(TEntity entity);  
  21.   
  22.   /// <summary>  
  23.   /// Commits all changes made so far  
  24.   /// </summary>  
  25.   void Commit();  
  26. }  


Finally, this is a possible implementation of a repository, using the DI pattern (and the ServiceLocator class):

  1. public class Repository<TEntity, TId> : IRepository<TEntity, TId>  
  2.   where TEntity : class, IEntity<TId>, new()  
  3. {  
  4.   protected readonly IEnumerable<TEntity> data;  
  5.   
  6.   public Repository(IEnumerable<TEntity> data)  
  7.   {  
  8.     this.data = data;  
  9.   }  
  10.  
  11.   #region IRepository<TEntity>  
  12.   
  13.   public virtual IEnumerable<TEntity> GetAll()  
  14.   {  
  15.     return data;  
  16.   }  
  17.   
  18.   public virtual IEnumerable<TEntity> FindAll(Expression<Func<TEntity, bool>> criteria)  
  19.   {  
  20.     var cond = criteria.Compile();  
  21.     return from entity in data where cond(entity) select entity;  
  22.   }  
  23.   
  24.   public virtual TEntity Find(Expression<Func<TEntity, bool>> criteria)  
  25.   {  
  26.     var cond = criteria.Compile();  
  27.     return (from entity in data where cond(entity) select entity).FirstOrDefault();  
  28.   }  
  29.   
  30.   public virtual TEntity Find(TId id)  
  31.   {  
  32.     return Find(entity => entity.Id.Equals(id));  
  33.   }  
  34.  
  35.   #endregion  
  36. }  


  1. public class LinqRepository<TEntity, TId> : Repository<TEntity, TId>, IUpdateableRepository<TEntity, TId>  
  2.   where TEntity : class, IEntity<TId>, new()  
  3. {  
  4.   protected readonly DataContext db;  
  5.   
  6.   public LinqRepository()  
  7.     : this(ServiceLocator.GetInstanceOf<DataContext>())  
  8.   {  
  9.   }  
  10.   
  11.   public LinqRepository(DataContext db)  
  12.     : base(db.GetTable<TEntity>())  
  13.   {  
  14.     this.db = db;  
  15.   }  
  16.  
  17.   #region IRepository<TEntity>  
  18.  
  19.   #endregion  
  20.  
  21.   #region IUpdateableRepository<TEntity>  
  22.   
  23.   public void Add(TEntity entity)  
  24.   {  
  25.     ((Table<TEntity>) data).InsertOnSubmit(entity);  
  26.   }  
  27.   
  28.   public void Delete(TEntity entity)  
  29.   {  
  30.     ((Table<TEntity>) data).DeleteOnSubmit(entity);  
  31.   }  
  32.   
  33.   public void Update(TEntity entity)  
  34.   {  
  35.     ((Table<TEntity>) data).Attach(entity, true);  
  36.   }  
  37.   
  38.   public void Commit()  
  39.   {  
  40.     db.SubmitChanges();  
  41.   }  
  42.  
  43.   #endregion  
  44. }  



Note: since I initially wrote this, I have read a few more articles discussing the need of using the Repository pattern at all. Here's a list of pro and con articles... decide for yourself :)

Ayende's article, first one I read on the subject.
Greg Young's first, second and third article.
Richard Dingwall's article.
This article suggests an interesting split - you should have two domains, one for changing your domain and one for querying it, and the two would have very different repositories. I have to think about it :)

ServiceLocator redivivus

This is the (so far) final form of the ServiceLocator class:


  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Reflection;  
  5.   
  6. namespace Helper  
  7. {  
  8.   public static class ServiceLocator  
  9.   {  
  10.     private static readonly Dictionary<Type, Func<object>> container = new Dictionary<Type, Func<object>>();  
  11.     private static readonly object containerLock = new object();  
  12.   
  13.     public static Func<Type, object> OnTypeNotFound =  
  14.       type => { throw new NotSupportedException("Cannot resolve type " + type); };  
  15.   
  16.     /// <summary>  
  17.     /// Discovers all the classes decorated with the Register attribute and registers them as implementations of the ImplementedType argument  
  18.     /// </summary>  
  19.     public static void Discover()  
  20.     {  
  21.       var types = Assembly.GetCallingAssembly().GetTypes().ToList();  
  22.       types.ForEach(type =>  
  23.                       {  
  24.                         var attr = type.GetCustomAttribute<RegisterAttribute>();  
  25.                         if (attr != null)  
  26.                           Register(attr.ImplementedType, () => Activator.CreateInstance(type));  
  27.                       });  
  28.     }  
  29.   
  30.     /// <summary>  
  31.     /// Helper function to return a custom attribute of a specified type  
  32.     /// </summary>  
  33.     /// <typeparam name="T">Desired type for the custom attribute</typeparam>  
  34.     /// <param name="type">Type searched for the custom attribute</param>  
  35.     /// <returns>The custom attribute or null if it was not found</returns>  
  36.     private static T GetCustomAttribute<T>(this ICustomAttributeProvider type) where T : class  
  37.     {  
  38.       return type.GetCustomAttributes(typeof (T), true).FirstOrDefault() as T;  
  39.     }  
  40.   
  41.     /// <summary>  
  42.     /// Maps the type T to a function returning T  
  43.     /// </summary>  
  44.     /// <typeparam name="T">Type requested by the application</typeparam>  
  45.     /// <param name="func">Function returning an instance of T</param>  
  46.     public static void Register<T>(Func<T> func) where T : class  
  47.     {  
  48.       Register(typeof (T), () => func());  
  49.     }  
  50.   
  51.     /// <summary>  
  52.     /// Maps the type T to a function returning T  
  53.     /// </summary>  
  54.     /// <param name="T">Type requested by the application</param>  
  55.     /// <param name="func">Function returning an instance of T</param>  
  56.     public static void Register(Type T, Func<object> func)  
  57.     {  
  58.       if (Contains(T))  
  59.         throw new ArgumentException("Type " + T + " already registered.");  
  60.   
  61.       lock (containerLock)  
  62.         container.Add(T, func);  
  63.     }  
  64.   
  65.     /// <summary>  
  66.     /// Removes the association for type T (for example as a preparation for another registration)  
  67.     /// </summary>  
  68.     /// <typeparam name="T">Type to unregister</typeparam>  
  69.     public static void Unregister<T>() where T : class  
  70.     {  
  71.       Unregister(typeof (T));  
  72.     }  
  73.   
  74.     /// <summary>  
  75.     /// Removes the association for type T (for example as a preparation for another registration)  
  76.     /// </summary>  
  77.     /// <param name="T">Type to unregister</param>  
  78.     public static void Unregister(Type T)  
  79.     {  
  80.       lock (containerLock)  
  81.         container.Remove(T);  
  82.     }  
  83.   
  84.     /// <summary>  
  85.     /// Returns true if the type T is registered  
  86.     /// </summary>  
  87.     /// <typeparam name="T">Type to check for an existing registration</typeparam>  
  88.     /// <returns>True if T is registered</returns>  
  89.     public static bool Contains<T>() where T : class  
  90.     {  
  91.       return Contains(typeof (T));  
  92.     }  
  93.   
  94.     /// <summary>  
  95.     /// Returns true if the type T is registered  
  96.     /// </summary>  
  97.     /// <param name="T">Type to check for an existing registration</param>  
  98.     /// <returns>True if T is registered</returns>  
  99.     public static bool Contains(Type T)  
  100.     {  
  101.       lock (containerLock)  
  102.         return container.ContainsKey(T);  
  103.     }  
  104.   
  105.     /// <summary>  
  106.     /// This is used by the application when it needs an instance of T  
  107.     /// </summary>  
  108.     /// <typeparam name="T">Type that the application needs an instance of</typeparam>  
  109.     /// <returns>An instance of T</returns>  
  110.     public static T GetInstanceOf<T>() where T : class  
  111.     {  
  112.       return GetInstanceOf(typeof (T)) as T;  
  113.     }  
  114.   
  115.     /// <summary>  
  116.     /// This is used by the application when it needs an instance of T  
  117.     /// </summary>  
  118.     /// <param name="T">Type that the application needs an instance of</param>  
  119.     /// <returns>An instance of T</returns>  
  120.     public static object GetInstanceOf(Type T)  
  121.     {  
  122.       lock (containerLock)  
  123.       {  
  124.         Func<object> result;  
  125.         if (container.TryGetValue(T, out result))  
  126.           return result();  
  127.       }  
  128.   
  129.       return OnTypeNotFound != null ? OnTypeNotFound(T) : null;  
  130.     }  
  131.   }  
  132. }  


Features:


  • OnTypeNotFound() - function mapping a type to an object if there is no explicit mapping for it. By default it will throw an exception, but you can replace it if you want, for example, to automatically Mock all types not explicitly mapped.

  • Discover() - this will inspect the calling assembly and automatically register as implementations all types decorated with the Register attribute.

  • Register() - maps a type (normally an interface type, but that's not required) to a Func<> returning an instance of that type. This allows, for example, a singleton implementation where the Func<> always returns the same object. Register() will throw if the type was already registered to avoid overwriting a registration by mistake; for intentional overwriting, use Unregister() first.

  • Unregister() - removes an existing mapping; does not throw even if one does not exist.

  • Contains() - can be used to verify that a type is registered, as GetInstanceOf() will by default throw if it's not.

  • GetInstanceOf() - this finds the function mapped to the given type and executes it, returning its result; if a mapping for this type is not found, GetInstanceOf() returns OnTypeNotFound() - which implicitly throws but can be overwritten.



The automatic registration (the Discover() method) needs implementation classes to be decorated with the Register attribute:


  1. using System;  
  2.   
  3. namespace Helper  
  4. {  
  5.   /// <summary>  
  6.   /// Use this attribute to decorate classes that should be registered as implementations of the argument   
  7.   /// </summary>  
  8.   /// <example>[Register(IRepository)]</example>  
  9.   [AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]  
  10.   public class RegisterAttribute : Attribute  
  11.   {  
  12.     public Type ImplementedType { getset; }  
  13.   
  14.     public RegisterAttribute()  
  15.     {  
  16.     }  
  17.   
  18.     public RegisterAttribute(Type implementedType)  
  19.     {  
  20.       ImplementedType = implementedType;  
  21.     }  
  22.   }  
  23. }  


Finally, I have also created a helper class for manual registration:


  1. using System;  
  2.   
  3. namespace Helper  
  4. {  
  5.   /// <summary>  
  6.   /// Fluent interface simplifying the registration of implementations  
  7.   /// </summary>  
  8.   /// <typeparam name="T">Type to implement</typeparam>  
  9.   /// <example>Bind&lt;IRepository&gt;.To(() => new Repository());</example>  
  10.   public static class Bind<T> where T : class  
  11.   {  
  12.     /// <summary>  
  13.     /// Maps T to Func&lt;T&gt;  
  14.     /// </summary>  
  15.     /// <param name="func">Function returning an instance of T</param>  
  16.     public static void To(Func<T> func)  
  17.     {  
  18.       ServiceLocator.Register(func);  
  19.     }  
  20.   }  
  21. }  


Decorating a class is obvious:

  1. [Register(typeof (DataContext))]  
  2. public partial class DBDataContext  
  3. {  
  4. }  


In the initial part of the application (like Global.asax.cs) you can do either this:

  1. ServiceLocator.Discover();  


or this:

  1. Bind<DataContext>.To(() => new DBDataContext());  
  2. Bind<IProductRepository>.To(() => new ProductRepository());  
  3. Bind<IImageRepository>.To(() => new ImageRepository());  


Finally (!), replace all "new class()" with:

  1. var repository = ServiceLocator.GetInstanceOf<IProductRepository>();  


In fact, it is recommended that you do not "hide" the dependencies, which means creating (usually) two constructors: one explicitly indicating dependencies and a default one calling the first, like this:

  1. public class ProductController : Controller  
  2. {  
  3.   private readonly IProductRepository repository;  
  4.   
  5.   public ProductController() : this(ServiceLocator.GetInstanceOf<IProductRepository>())  
  6.   {  
  7.   }  
  8.   
  9.   public ProductController(IProductRepository repository)  
  10.   {  
  11.     this.repository = repository;  
  12.   }  
  13. }  


Whew :) Please let me know if this helps, or if you find any problems with it :)

Sunday, December 28, 2008

5-minute dependency injection container in C#

I found Misko Hevery's talks on the usefulness of Dependency Injection to be quite persuasive, so I have started using constructor DI in my projects. Unfortunately, some of those involve ASP.NET WebForms applications, and even in the one I just started using ASP.NET MVC there are classes I do not create myself (like the controllers). This means that when I write something like

  1. public class ProductController  
  2. {  
  3.   private ProductRepository repository;  
  4.   
  5.   public ProductController()  
  6.   {  
  7.     repository = new ProductRepository();  
  8.   }  
  9. }  


I am hard-coding a dependency on the concrete ProductRepository class inside ProductController.

There are (at least) two solutions to this. One of them would be to create a property in the ProductController class:

  1. public IProductRepository Repository { getset; }  


and change the constructor to

  1. public ProductController()  
  2. {  
  3.   Repository = new ProductRepository();  
  4. }  


This is the usual property dependency injection, and it works quite well. However, I find it annoying to do this for every class, not to mention that I don't like the idea of adding a public property just so I can test the class, since this breaks the information hiding tenet.

A variant of this option is to have two constructors:

  1. public ProductController(): this(new ProductRepository())  
  2. {  
  3. }  
  4.   
  5. public ProductController(IProductRepository repository)  
  6. {  
  7.   Repository = repository;  
  8. }  


A second option would be to use a DI container and do this:

  1. public ProductController()  
  2. {  
  3.   repository = Container.Get<IProductRepository>();  
  4. }  


and somehow instruct the program, in the initialization part (like Global.asax.cs), to return a new ProductRepository instance every time I ask for an IProductRepository.

This seems to me a bit more fluent, however the association part in (most of) the existing DI containers seem to be overkill.

So... I came up with a home-made DI container by using the pattern in my previous post:

  1. public class GenericContainer  
  2. {  
  3.   private static readonly Dictionary<Type, Func<object>> container =  
  4.     new Dictionary<Type, Func<object>>();  
  5.   
  6.   public static void Register<T>(Func<T> func) where T : class  
  7.   {  
  8.     container.Add(typeof (T), () => func());  
  9.   }  
  10.   
  11.   public static void Unregister<T>() where T : class  
  12.   {  
  13.     container.Remove(typeof (T));  
  14.   }  
  15.   
  16.   public static T Get<T>() where T : class  
  17.   {  
  18.     return container[typeof (T)]() as T;  
  19.   }  
  20. }  


(The Register() method uses a trick here to convert a Func<T> to a Func<object> so that it can be saved in the dictionary - I should be able to get rid of this once we get covariance / contravariance in .NET 4.0 and Visual Studio 2010.)

The usage is quite simple - this call will associate a type with a function returning instances of that type:

  1. GenericContainer.Register<IProductRepository>(() => new ProductRepository());  


and this call will replace the "new ProductRepository()" call:

  1. GenericContainer.Get<IProductRepository>();  


(Of course, I don't have to use interfaces here; I can use any type.)

Note that the flexibility of the function allows me to also handle the use cases where I want a singleton returned:

  1. var productRepository = new ProductRepository();  
  2. GenericContainer.Register<IProductRepository>(() => productRepository);  


During testing I will want to replace the object being returned with a mock object I control:

  1. GenericContainer.Register<IProductRepository>(() => new MockProductRepository());  


It's that simple!

As you can see, I'm quite excited about this... it might not have all the bells and whistles of a mainstream DI container, but I find it quite good for what I need.

Edit: Ok, this might be more of a Service Locator pattern instead of Dependency Injection... I am unclear on the terminology. Useful in any case, though :)

Edit 2: It looks like this pattern does have a problem: it hides dependencies. The constructor dependency injection shows clearly that class A depends on classes B, C, and D. Using a service locator hides that. I think the compromise suggested in the article - create two constructors, one exposing the dependencies and one using the service locator - is the best way for now.

Thursday, December 11, 2008

Important pattern in C#

While programming, one sometimes needs static methods - methods that cannot meaningfully be associated with an object (a class instance). One example that comes to mind is Math.Abs, but Factory.CreateCustomer might be another. On the other hand, static methods make the methods that use them hard to test - what do you do if you try to test a method that calls Factory.CreateCustomer()? You don't want it to do that, you might want to return a fake customer, or null, or a NullCustomer - any of a number of choices.

One solution - the most recommended one, in fact, as far as I can tell - is to extract the method in an interface (IFactory.CreateCustomer) and pass an instance of that interface to either the constructor of the class under test, or directly to the tested method. Which is nice, except sometimes you can't alter the constructor of a class (like Pages in ASP.NET and Entities when working with Linq to Sql), and passing the interface to each method looks somewhat ugly.

A few days ago I found another method (I think it was on Ayende's blog, but I'm not sure):

  1. public static class Factory  
  2. {  
  3.   public static Func<int?, Customer> FindCustomer = customerID => GetDB().FindCustomer(CustomerID);  
  4. }  


This declares FindCustomer as a delegate to a function taking a nullable int (the customer ID) and returning a Customer, and initializes this delegate to point to a specific function. However, and here is the great part, nothing prevents one from overwriting this function in testing to return a mock customer or whatever.

It's too early for me to tell if this is a great idea or a bad one, so I might change my mind later; but so far I'm pleased with it.