Thursday, October 28, 2010

Static cache

Let's try to resolve a pretty regular case - some kind of key-value static cache. If there is no stored value for the specified key, the cache will call some external routine to get value and add it to the internal dictionary.

Here is a naive approach of the cache. It is straightforward enough.

public class Cache<TKey, TValue>
{
  Func<TKey, TValue> _resolver;
  Dictionary<TKey, TValue> _cache = new Dictionary<TKey, TValue>();

  public Cache(Func<TKey, TValue> resolver)
  {
    _resolver = resolver;
  }

  public TValue this[TKey key]
  {
    get
    {
       TValue value;
       if (!_cache.TryGetValue(key, out value))
       {
         value = _resolver(key);
         _cache.Add(key, value);
       }
       return value;
    }
  }
}

And also somewhere in a client code:
class ClientCode
{
  static Cache<TKey, TValue> _cache = new Cache<TKey, TValue>(Resolver);
}
Where Resolver is an user-defined function to get a value from the outer source.

Tuesday, October 12, 2010

Order zen

Pretty interesting question (and a good one for interview as well).

An Enumerable class contains two sets of methods: OrderBy() and ThenBy(). The first set sorts the elements of a sequence, second one performs a subsequent ordering of the elements in a sequence. If you have a sequence of names as {FirstName, LastName} and what to sort it by first name and then by last name you probably will not write as following:
var sorted = names.OrderBy(x=>x.FirstName).OrderBy(x=>x.LastName)

This is obviously wrong because you will firstly sort the sequence by FirstName and then resort it by LastName. To do the requested thing, you'll write:
var sorted = names.OrderBy(x=>x.FirstName).ThenBy(x=>x.LastName)

And here is the question - how ThenBy() is implemented (or how would you implement ThenBy() method)?

Monday, October 11, 2010

The vassal of my vassal is not my vassal

Just a thumb rule - avoid creating a PropertyExpression using

public static MemberExpression Expression.Property(Expression expression, MethodInfo property)

Instead prefer

public static MemberExpression Expression.Property(Expression expression, PropertyInfo property)

Tuesday, October 5, 2010

Interview

I would like to ask the following questions/tasks on a technical interview.
  1. Implement a singleton.
    Yes, kinda boring question. But I'll expect simple implementation, like follows:

    public class Singleton{
      private Singleton(){}
      public static Singleton Instance = new Singleton();
    }

    and nothing more. There is no words about laziness. Anything more complicated signals about over-engineering.
  2. Implement (I)Disposable pattern. And after it - When does a type need a finalizer?
    Second part is simple, first part is not good without explanation. In this case I'll wait for

    protected virtual void Dispose(bool isDisposing)

     
  3. ...to be continued