Skip to main content

Command Palette

Search for a command to run...

Code Smell 49 - Caches

Updated
2 min read
Code Smell 49 - Caches
M

I’m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.

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

TL;DR: Any junior student can create a cache. Almost no senior developer can debug and invalidate them.

Problems

  • Coupling

  • Testability

  • Cache invalidation.

  • Maintainability

  • Premature Optimization

  • Erratic Behavior

  • Lack of transparency

  • Non-Deterministic behavior

Solutions

  1. If you have a conclusive benchmark and are willing to pay for some coupling: Put an object in the middle.

  2. Unit test all your invalidation scenarios. Experience shows we face them in an incremental way.

  3. 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

Credits

Photo by Aimee Vogelsang on Unsplash


There are only two hard things in Computer Science: cache invalidation and naming things.

Phil Karlton



This article is part of the CodeSmell Series.

M

Hey Maxi, love all the series about the Code smell :-).

Just a curious about this line return $this->inbox->retrieveAndRemove($title);

Here, we retrieve the title from cache and remove it immediately? Why do we retrieve and remove? Wouldn't it increase the write-to-cache ratio by deleting cache quite often :-) ? whats your thoughts on that?

M

It is about the real life metaphore on retrieving an existing copy (and using it) If you have fungible objects (A real life book is not) you could just retrieve it and keep it. It is like aquiring a lock in this case

1

Code Smells

Part 1 of 50

In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.