Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

We\'ve started implementing some caching code in our MVC project. We\'ve derived

ID: 643755 • Letter: W

Question

We've started implementing some caching code in our MVC project. We've derived from .Net's ObjectCache to store it in a SQL database.

What we do right now is in each method we want to cache we have code like this:

public StatusCounts GetCounts()
{
   var cache = new SqlCache<StatusCounts>("mykey");
   if(cache.HasCachedData())
      return cache.GetCachedData();

   var data = StatusRepository.GetCounts();

   cache.SetData(data, DateTime.Now.AddHours(2));
}
As far as caching goes, it works. But my concern is it seems like now GetCounts has multiple responsibilities. It's no longer just calculating counts, it's getting them from a cache (if they exist) and saving them to a cache before returning.

Is there a cleaner way to do this?

Explanation / Answer

You can separate the cache initialization from returning the value, and implement the cache initialization in a generic way:

public StatusCounts GetCounts()
{
var cache = GetInitializedCache<StatusCounts>("mykey",StatusRepository.GetCounts,2);
return cache.GetCachedData();
}

private SqlCache<T> GetInitializedCache<T>(string key,Function<T> getData,double hours)
{
var cache = new SqlCache<T>(key);
if(!cache.HasCachedData())
{
T data = getData();
cache.SetData(data, DateTime.Now.AddHours(hours));
}
return cache;
}
That will separate the concerns of caching and calculating the values as well as giving you a reusable function. Of course, the method body of GetCounts is still aware of the caching mechanics, and if you want to avoid that too, @Peri's answer maybe the right approach (for the price of having to introduce a non-trivial third-party component).

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote