Google warns against prematurely applying the DRY principle to your code

Google Testing Blog: Don't DRY Your Code Prematurely
https://testing.googleblog.com/2024/05/dont-dry-your-code-prematurely.html

DRY stands for 'Don't Repeat Yourself' and is a philosophy that emphasizes not duplicating code. If there is duplicated code, when you try to change a specific function, you have to find all parts of the code that have the same function and change them at the same time, which increases the risk of oversights or mistakes. On the other hand, if you can prevent code duplication, you only need to change one place.
While strict application of DRY may seem like a good idea because it improves code maintainability, Google's Code Health group wrote in a blog post that 'applying DRY too strictly can lead to premature abstraction, making future changes unnecessarily complex,' and warned that premature application of DRY should be avoided.
For example, the code on the left below combines 'deadline determination' into a single function in accordance with DRY, while the code on the right is split into two, violating DRY. The 'ValueError' checks are identical, so DRY is currently applicable, but the Code Health group argues that DRY should not be applied, stating that 'task and payment deadlines are different concepts with different logic, and the checks are simply the same by chance.'

In fact, if additional validation is required for payments, it's easy to add it to the code on the right, but it's very difficult to introduce 'additional validation for payments' into the code on the left. 'Careful consideration is needed to determine whether the code is truly redundant or only superficially similar,' the article states.
Because code requirements often change over time, it's easier to tolerate some overlap in early or small-scale development, and then start abstracting once enough common patterns emerge that it's clear to apply DRY.
Related Posts:







