This is part 4 of the Clean code for kids series. In part 1 we said why code is read more than it's written, in part 2, why names are documentation for free, and in part 3, why a method and a class do only one thing. And part 3 ended with the sentence we start with today: when you feel the temptation "I'd extract this into a shared class", come here. Because between "I'm repeating myself" and "I'll create an abstraction" is a thin line ... and both sides of that line can be shot.
DRY: Don't Repeat Yourself
Imagine writing two cookbooks and having the pancake recipe in both. A year later you find out pancakes need less sugar. You fix the first book… and forget the second. Now you have two books claiming two different things about the same dish. Which one is true? You don't know.
It's the same with code. When **the same decision is written in two places**, you have two sources of truth. Over time they drift apart ...
someone fixes one, forgets the other, and suddenly the same page shows two different results depending on which code it went through.
That's what we call DRY ... Don't Repeat Yourself. It's not "write as few lines as possible". It's one decision = one place. Every rule about code has its one place of truth.
Real case: resolveCover() in two places
And now the best part ... this repo had real duplication of exactly this kind, and we can break it down. *(Since this article was published, it was fixed exactly as described below ... BlogArticleAction today calls BlogArticlesService. The code that follows shows how it looked before the fix ... and from it you'll learn to recognize duplication.)*
The article cover image is chosen by priority:
- front matter
image(the author explicitly set it), - a local SVG in
storage/blog-images/{slug}.svg(generated), - a Cloudinary pool (deterministic fallback by slug hash).
This decision is written in BlogArticlesService ... the service that makes the cards on the /blog index:
// BlogArticlesService.php
private function resolveCover(string $slug, array $meta): string
{
// 1. Explicit image from front matter
if (is_string($meta['image'] ?? null) && '' !== $meta['image']) {
return $meta['image'];
}
// 2. Local SVG file (generated by bin/cms generate-images)
$svgPath = AppPaths::instance()->storage('blog-images' . DIRECTORY_SEPARATOR . $slug . '.svg');
if (is_file($svgPath)) {
return '/storage/blog-images/' . $slug . '.svg';
}
// 3. Cloudinary pool fallback
return self::COVER_IMAGES[abs(crc32($slug)) % count(self::COVER_IMAGES)];
}
…and exactly the same is in BlogArticleAction ... the action that renders the article page /blog/{slug}:
// BlogArticleAction.php
private function resolveCover(string $slug, array $meta): string
{
// 1. Explicit image from front matter
if (is_string($meta['image'] ?? null) && '' !== $meta['image']) {
return $meta['image'];
}
// 2. Local SVG file (generated by bin/cms generate-images)
$svgPath = AppPaths::instance()->storage('blog-images' . DIRECTORY_SEPARATOR . $slug . '.svg');
if (is_file($svgPath)) {
return '/storage/blog-images/' . $slug . '.svg';
}
// 3. Cloudinary pool fallback
return self::coverPool()[abs(crc32($slug)) % 4];
}
Notice: these aren't two similar methods ... it's **the same method, copied**. Same comments, same logic, same step order. That's not a coincidence: one of the two places is duplication.
Why it's dangerous ... and where it already drifts apart
Duplication doesn't hurt at the moment you write it. It hurts at the next change. Look at the last line of both methods:
BlogArticlesService:self::COVER_IMAGES[abs(crc32($slug)) % count(self::COVER_IMAGES)]BlogArticleAction:self::coverPool()[abs(crc32($slug)) % 4]
That difference isn't just cosmetic. The image pool lives in **two places**: in the COVER_IMAGES constant in the service and in the coverPool() method in the action. As if you wrote the pancake recipe into two books ... one with "3 eggs", the other with "3".
Now imagine someone adds a fifth image to the pool. In BlogArticlesService it handles itself via count(self::COVER_IMAGES) ... it finds there are 5 and the index reaches all five. But in BlogArticleAction there's a hardcoded % 4 ... the article page stays at four. Suddenly the fifth image is invisible, but only on one page. How do you find it? There's no error, no stack trace. Just two pages that don't match.
And that's exactly the moment when duplication stops being an annoyance and becomes a smoke signal: two places with the same decision drift apart over time. Not "they might", but "they will" ... because every change is made in one place and the other stays.
What to do about it: one source of truth
The solution isn't writing a third copy. The solution is **letting one place make the decision and having the other place only ask it**. In this case BlogArticleAction no longer has its own resolveCover() at all ... there's a service that computes the cover image, and the action just calls it:
// today: one place decides, the other asks
$articles = new BlogArticlesService($resolver);
// …
$coverImage = $this->coverImage($slug, $meta, $articles);
That's exactly how the rest of the article page works:BlogArticleAction doesn't decide about the author itself, it calls BlogAuthorResolver; it doesn't make avatar markup, it calls AuthorAvatar (part 3). Composition instead of a copy. The cover was once an exception ... and exceptions in DRY are exactly the places where bugs are born. Today it's composition too, and a fifth image in the pool would appear on both pages at once, because both ask the same method.
The smoke signal that remained
And the best part ... the duplication didn't remain just an article. It left behind a lesson and a regression test: a test guards that the article page and the index always show the same cover for the same slug. If someone returned to duplication (say, hardcoded % 4 again), the test would fail ... exactly as we learned in part 5, that smoke tests guard the rules for you.
*(And this is the point of the whole part: duplication can not only be recognized, but also fixed. This particular one was removed after the article was published ... the action now calls $articles->resolveCover() and the only copy lives in the service, with a regression test guarding that the index and the article always show the same cover. The article is about how to recognize duplication; the fix was a separate change, with its own test.)*
The other side of the coin: premature abstraction
And now the other side, because DRY can be abused. Once you learn "don't repeat yourself", it's easy to slide into: **"so I'll put everything behind an interface!"** An interface is after all an abstraction ... one definition, many uses, no duplication. Sounds tempting. It's a trap.
An interface is a contract for the outside world ... a promise that "whatever implements this will know how to do this". But when your abstraction has one consumer and one implementation, it's not a contract. It's decoration. You unify nothing ... you just add a layer every reader must chew through to learn that there's a single class behind it.
An analogy: you don't buy all the tools for your workshop in advance, "so you can use them someday". You buy a screwdriver when you have a screw. You create an interface when you have a **second implementation** ... not before.
And this repo enforces it with a test (baseline 0)
Of course, it's not just a recommendation. In part 1 we showed that this project writes rules as tests ... and this one too is in tests/Architecture/CorePatternTest.php:
/**
* Baseline: number of interfaces with exactly one implementation in the
* same feature module and no consumer outside that module. Raising this
* constant is NOT the fix ... removing a speculative interface is.
*/
private const SPECULATIVE_INTERFACE_BASELINE = 0;
The test testNoSpeculativeSingleImplementationInterfaces() walks all of src/, finds every interface, counts its implementations ... and if it has exactly one implementation in the same module and **no consumer** outside it, that's a speculative abstraction. Violation. Red build.
And watch out for that comment ... *"raising this constant is NOT the fix"*. When the test fails, the temptation is to raise the baseline from 0 to 1. But that's exactly like saying "the rule no longer applies".
The fix is to remove the speculative interface ... use the concrete class directly. The test is written to lead you to the right fix, not to switch it off.
Why LocalStorageProvider has no interface
Look at a real class from this repo ... LocalStorageProvider:
// BlogArticlesService.php ... no StorageProviderInterface, just a concrete class
private function avatar(): AuthorAvatar
{
return $this->avatar ??= new AuthorAvatar(new LocalStorageProvider());
}
It's called directly via new LocalStorageProvider() in seven places across the project ... in AuthorAvatar, UsersAction, ServeUploadedFileAction, AuthorProfileAction… And it **has no interface**. Why? Because it has exactly one implementation and exactly one way of being used. If someone created a StorageProviderInterface, the test testNoSpeculativeSingleImplementationInterfaces() would fail ... and that's correct. An interface would add nothing but a layer.
When would an interface make sense? When a second provider arrives ...
for example an S3StorageProvider for production deployments. Then you have two implementations, two reasons to choose, and the contract "whatever can store() and delete() is a storage" becomes useful.
But until then: a concrete class, directly, without an intermediate step.
The exception the test respects: interfaces in Modules\Core and Modules\Database are the shared kernel's contract ... "libc headers". Those are interfaces for the outside world (other modules), not internal abstraction, and the baseline doesn't count them.
Decision tree: duplication or abstraction?
When you feel "this repeats itself", run through three questions ... in this order:
- Is it really the same thing? Does it change for the same
reason? If yes ... unify (one source of truth, part 3: one reason to change).
- Is it just similar, but changes for a different reason? Then
it's not duplication, it's a coincidence ... and unifying would be worse. Two methods that look the same but answer different questions would start changing together once unified. That's **premature abstraction**.
- Do you have a second implementation? An interface isn't about
something repeating ... it's about more than one way of doing it. One implementation = no interface. Two = a contract.
And finally one rule that saves you the most trouble: **abstract when the duplication appears ... not when you predict it.** The first copy is often fine (maybe the second never comes), the second copy is the moment you start thinking, and the third copy is the moment you unify.
Nobody requires you to be a prophet ... you're required to count how many copies you have.
Summary of part 4
- DRY = one decision, one place ... not as few lines as possible.
Two copies of the same thing are two sources of truth that drift apart.
- Real example ...
resolveCover()once lived in both
BlogArticlesService and BlogArticleAction, with a diverging detail (count() vs % 4), and today it's one source of truth.
That's exactly what duplication looks like in practice: it doesn't hurt when you write it, it hurts at the change.
- DRY can be abused ... "everything behind an interface" is
premature abstraction. An interface is a contract for the outside world, not decoration.
- The test enforces it ...
SPECULATIVE_INTERFACE_BASELINE = 0:
an interface with one implementation = violation.
LocalStorageProvider correctly doesn't have one.
- The decision tree ... the same thing? Unify. Similar but a
different reason to change? Leave it. A second implementation? Only now an interface.
- Link to the next part ... all these rules are enforced by tests,
and about how tests work as warning smoke signals ... and how they're written so they can't be bypassed ... is part 5.
Sources
- PHP Manual: official PHP documentation
- PHP-FIG, PSR Standards: PHP standards
- OWASP Cheat Sheet Series: security best practices
- Nativa Minimal Documentation: official getting started guide
- W3C, Web Standards: web standards
Comments (0)
No comments yet — be the first to react.