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.
Five Blogs – 26 March 2012 « 5blogs wrote:
[…] Build a Cache, not a Stash Written by: George Dinwiddie […]
Posted on 26-Mar-12 at 7:55 am | Permalink
Paul Nelson wrote:
This is definitely good advice. Of course, the next step in this particular journey is to creatively find ways to make nearly every request a “repeat” request.
37Signals has an excellent post on taking caching this next step (specifically, the “Caching TO THE MAX) section: http://37signals.com/svn/posts/3112-how-basecamp-next-got-to-be-so-damn-fast-without-using-much-client-side-ui
Posted on 27-Mar-12 at 1:41 pm | Permalink