Wednesday 18 May 2011

Null values in dictionaries

Eeek! Why on Earth would someone insert null values into a dictionary? Especially when one sees code like


Dictionary<A,B> d = new Dictionary<A,B>();


blah


TryGetValue( key, out value);
if(value==null) throw new Exception();


That is to say that the return value from TryGetValue is routinely ignored and instead the null-ness of the output value is used to indicate failure. Clearly this has been written because the original author didn't want to wrap dictionary access in try ... catch(), which is understandable, but ...

So I propose that null indicates failure. With this in mind, we can rewrite TryGetValue as follows:


public static Nullable<V> TryGetValue(Dictionary<K,V> d, K key)
{
V v;
bool s = d.TryGetValue(key, out v);
return s ? v : (Nullable<V>)null;
}


This is, of course, absolutely spiffing because now TryGetValue is a function which returns the sought value and so lends itself to a declarative programming style.

Also, with the parameters in the order key then dictionary we allow ourselves the possibility of function pipelining.

No comments:

Post a Comment