Caching and the SRP
I've been using Velocity (Microsofts new caching product) on a project and while lurking on the lists spotted a post about testability around the Velocity API's. There may be reasons for doing this but it is something I avoid. I tend to use the SRP principle when it comes to anything that is associated with crosscutting concerns in my code (Caching, Logging, Session etc). As such I have one class that just deals with caching, a simple example would be.
1: public interface ICache
2: { 3: void Add(Basket res, string key);
4: Basket Get(string key);
5: void Remove(string key);
6: }
1: public class Velocity : ICache
2: { 3: private const string CACHE = "MyCache";
4:
5: public void Add(Basket res, string key)
6: { 7: var CacheCluster1 = new CacheFactory();
8: var Cache1 = CacheCluster1.GetCache(CACHE);
9: Cache1.Add(key, res);
10: }
11:
12: public Basket Get(string key)
13: { 14: var CacheCluster1 = new CacheFactory();
15: var Cache1 = CacheCluster1.GetCache(CACHE);
16:
17: return (Basket) Cache1.Get(key);
18: }
19:
20: public void Remove(string key)
21: { 22: var CacheCluster1 = new CacheFactory();
23: var Cache1 = CacheCluster1.GetCache(CACHE);
24:
25: Cache1.Remove(key);
26: }
27: }
So simple actions for Add, Remove, Get that wrap up what Velocity is doing. The rest of my code just needs to know about this class with rest of the details abstracted away. If I wanted I could use memcache rather than Velocity, as long as my memcache class implements ICache my code is not concerned, all it is concerned with is a class that implements ICache.
1: var cacheValue = cache.Get(basketid);
2: if(cacheValue == null)
3: { 4: var res = GetBasket(basketid);
5: if(res != null)
6: { 7: cache.Add(res, cachekey);
8: }
9: return res;
10: }
11: return cacheValue;
Know you can use DI to inject your caching class, using the IOC this would simply be
1: IOC.Register<ICache, Velocity>();
Neat.