End Up With Caching Boring Code

boring2The situation is always the same: You are building a new feature that retrieve some data, make some calculus or whatever, and you think that is appropriated to cache the results for some while, and here is the cache aside pattern been written over and over again:

           if (!CachingContext.Current.Contains("YourKey"))
                var result = GetAnyResult();

                 CachingContext.Current.Add("YourKey", result, ExpirationType.Absolute, 10);

                 return result;
                return CachingContext.Current.GetData("YourKey");

The pattern is nice, some developers when working with multi-thread applications like to use the statement “lock” in combination with this pattern to avoid concurrency issues, but the truth is: this structure of code is replicated in every method that needs to cache something.

One tip to avoid writing this boring code structure is to combine the caching aside pattern, with Func and anonymous methods.

Here is an example about how to code the Cache Aside Pattern in a unique method:

public TResult ManageCache<TResult>(Func<TResult> txCode, string cacheKey, ExpirationType expirationType, double minutes)
        TResult result;

        if (!CachingContext.Current.Contains(cacheKey))
            result = txCode();

            CachingContext.Current.Add(cacheKey, result, expirationType, minutes);
            result = (TResult)CachingContext.Current.GetData(cacheKey);

         return result;

And How should you call it:

 var result = CachingContext.Current.ManageCache(() =>
                    return GetAnyResult();

It´s pretty simple and you still use the cache aside pattern, but don’t need to repeat the boring code structure every time you want to use it.


About Rafael Tolotti

Brazilian software architect, post graduated in Strategic Management of Information Technology. Microsoft Commerce Server specialist interested in software architectures and design patterns. He's also interested in team management, risk management, project management and agile software development. As a sports lover is passionate about soccer and tennis as well.
This entry was posted in .NET Framework, Computer Science and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s