Build a Cache, not a Stash

There are many times where a call to get some data is time-consuming or expensive. Perhaps it makes a webservice call, or a network connection to a database, or iterates over a large collection to perform a calculation. If the values isn’t going to change rapidly, and might be needed again soon, it’s natural to want to save the value for that use.

Things get a little more complicated when the next use isn’t immediate, or is under the control of external events. Perhaps it depends on what links a user clicks on the UI. No problem—we build a storage mechanism a bit more complex than a variable.

What’s wrong with that?

The problem arises when the code that uses the value has to check in two places for it. Oops! We haven’t build a cache, even if we call it that. Instead the code is just stashing the value in a temporary place. The fact that our code has to check two places is a dead giveaway that we’ve violated the single responsibility principle.

Instead, let our code call for the value as it’s always done. Build a caching facade that sits in front of the expensive call and offers the same API. This facade will have only one purpose: caching those results and returning the cached value if the same request is made. Our original code will have only one purpose: whatever it’s doing that requires it to need those results.

It’s a simple thing, and it avoids a common mistake that introduces complexity and accompanying defects.

2 Replies to “Build a Cache, not a Stash”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.