Ok, I’ve just started working with Microsoft’s Distributed Caching API (aka “Velocity”) and while I’m very happy with the features thus far (can’t wait for notifications!), I really think the API needs a TryGetValue method. Right now you have the Get, GetAndLock and GetIfNewer methods and all of those return type Object. My suggestion is two-fold:
- Add the TryGetValue method with similar overloads to Get. Return a bool which, if true, indicates the item was found.
- Take it a step further and make the method generic. This will help when working with simple value types like DateTime, Int32, Guid, etc.
Imagine you’re caching a DateTime and want to look it up… here’s an example of how you need to do that with the API today:
object cacheValue = cache.Get(“MyCachedDateTime”);
DateTime myDateTime; if(cacheValue != null)
{
myDateTime = (DateTime)cacheValue;
}
else
{
myDateTime = CalculateSomeComplicatedDateTime();cache.Add(“MyCachedDateTime”, myDateTime);
}// … use myDateTime here …
Notice the annoying need to have a temporary object variable (“cacheValue” in the sample). You need that because you can’t cast straight to a value type like DateTime. Now let’s look at what it might look like with the TryGetValue implementation I’m suggestion:
DateTime myDateTime;
if(!cache.TryGetValue<DateTime>(“MyCachedDateTime”, out myDateTime))
{
myDateTime = CalculateSomeComplicatedDateTime();cache.Add(“MyCachedDateTime”, myDateTime);
}// … use myDateTime here …
There’s no denying the second version results in less code and, IMHO, this pattern is far more legible.
How about writing an extension method, e.g. this one:public static T Get<T>(this Cache cache, string key, Func<T> creator){ T val = (T)cache.Get(key); if(val == default(T)) { val = creator(); cache.Add(key, val); } return val;}and then you could callDateTime myDateTime = cache.Get<DateTime>(“MyCachedDateTime”, () => CalculateSomeComplicatedDateTime());