The "not quite the same" problem
Here’s a scenario:
You’re adding an "Edit Post" feature to your tiny social media website project.
You already have a "New Post" feature. Editing seems nearly identical: You edit the text, submit it, etc.
Creating and editing are nearly the same thing!
Surely we can re-use the creation code for our editing feature. And the DRY (Don’t Repeat Yourself) principle urges us to consider ways this nearly-the-same code can handle both tasks. (Or does it? See below!)
But experience has taught me to do it the dumb way first. And the "dumb" way is to not share the code. Just go ahead and make a copy of it.
I already new the outcome. Copying the code and modifying it for the edit process was much cleaner than trying to share the code. I’ve done a million of these so-called CRUD interfaces and it’s always the same story.
Yeah, I end up with some really annoying repetition and if I change the name of "post" to "missive", I’ve gotta go changing that in twice as many places.
But, this annoying repetition is not the worst sin you could commit in this codebase. Chasing abstraction so far that you end up with a confusing maze of logic - and quite possibly more code to support the abstraction than a second copy - is much worse.
Trying to abstract out the differences between creating a new post and editing an existing post is something every developer should try at least once. I had to attempt it many times before the wisdom finally stuck. I could try to list the reasons, but you really just have to try it to see. Friction in Software Development must be experienced first-hand.
The real DRY principle
The version of DRY I first read was in The Pragmatic Programmer by Andy Hunt and Dave Thomas and it reads:
"Every piece of knowledge must have a single, unambiguous, authoritative representation within a system".
Note that it doesn’t say anything about code repetition, per se.
Code is knowledge. That’s absolutely true.
But the logic for creating a post and editing a post are two different pieces of knowledge. Similar, yes. But not quite the same. It’s okay that they have separate complete representations.
A DRY bakery is not compelled to create a "macaro+n" cookie which attempts to satisfy the properties of both a "macaron" and "macaroon" just because they are spelled so similarly and are both sweet baked goods.
It’s perfectly fine to have both.