Google urges developers not to prematurely apply DRY principles to their code



Code Health , a group that works to keep the code at Google readable and maintainable, has published an article titled 'Don't be too premature with DRY .'

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



DRY is an abbreviation for 'Don't Repeat Yourself' and is a way of thinking that emphasizes not duplicating code. If there is duplicated code, when you try to change a specific function, you have to find all the parts with the same function and change them at the same time, which increases the risk of overlooking something or making a mistake. On the other hand, if you can prevent code duplication, you only need to change one place.

At first glance, strict application of DRY seems like a good thing because it improves code maintainability, but Google's Code Health group wrote in a blog post that premature application of DRY should be avoided, saying, 'Applying DRY too strictly can lead to premature abstraction, making future changes unnecessarily complicated.'

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' check contents are the same, and DRY can be applied at present, but the Code Health group believes that DRY should not be applied, because 'tasks and payment deadlines are different concepts with different logic, and the check contents are just the same by coincidence.'



In fact, if additional validation is required for payments, it is easy to add validation to the code on the right, but it is very difficult to introduce 'additional validation for payments' to the code on the left. 'Careful consideration must be given to whether the code is truly redundant or only superficially similar,' it 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 that DRY is needed.

in Software, Posted by log1d_ts