Code Smell 49 — Caches
Caches are sexy. They are a one-night stand. We need to avoid them in a long-term relationship.

Problems
- Coupling
- Testability
- Cache invalidation.
- Maintainability
- Premature Optimization
- Erratic Behavior
- Lack of transparency
- Non-Deterministic behavior
Solutions
- If you have a conclusive benchmark and are willing to pay for some coupling: Put an object in the middle.
- Unit test all your invalidation scenarios. Experience shows we face them in an incremental way.
- Look for a real world cache metaphor and model it.
Sample Code
Wrong
Right
Detection
This is a design smell.
It will be difficult to enforce by policy.
Tags
- Premature Optimization
Conclusion
Caches should be functional and intelligent.
In this way we can manage invalidation.
General purpose caches are suitable only for low level objects like operating systems, files and streams.
We shouldn’t cache domain objects.
This page is hosted on a cached website.
Relations
More Info
There are only two hard things in Computer Science: cache invalidation and naming things.
Phil Karlton
This article is part of the CodeSmell Series.