𝗖𝗼𝗱𝗲 𝗗𝘂𝗽𝗹𝗶𝗰𝗮𝘁𝗶𝗼𝗻 𝗜𝘀 𝗖𝗵𝗲𝗮𝗽𝗲𝗿 𝗧𝗵𝗮𝗻 𝗪𝗿𝗼𝗻𝗴 𝗔𝗯𝘀𝘁𝗿𝗮𝗰𝘁𝗶𝗼𝗻𝘀
Most developers learn the DRY principle early. Do Not Repeat Yourself.
This rule makes sense. It stops errors and saves time.
But many developers follow this rule too strictly. They try to merge everything into one function or class. This leads to over-engineering.
When you force two different pieces of logic into one abstraction, you create problems. You add complexity. You make the code hard to read.
A wrong abstraction costs more than a little duplication.
If you duplicate code, you know exactly where the logic lives. If you need to change one part, you change it there.
If you use a bad abstraction, you must change everything connected to it. You risk breaking features that have nothing to do with your current task.
Follow these rules to stay safe:
- Write code for the task at hand.
- Wait for a pattern to emerge three times before you abstract.
- Prioritize readability over saving a few lines of code.
- Accept that some duplication is healthy.
Stop trying to make every line of code perfect. Focus on making your code easy to change.