Skip to content

Duplicate code isn’t that bad

Duplicate code isn’t something we want in our code for various reasons. Clearly, the straightforward reason is changing the duplicate code. You need to find the same code piece everywhere it’s used and replace them all. A more complicated reason is the proper use of design principles [1]. Although it’s hard to argue against any of the reasons, I still think duplicate code can be fine.

Duplicate code can make your code more readable and understandable. We all know the duplicate code is against don’t repeat yourself; however, our goal isn’t really DRY. DRY and other principles are tools to achieve maintainability and readability. As we have a more readable and understandable code, then we have a better readability and maintainability. By far the best example for this purpose is setup code for testing. You could possibly create a function but it would be hard to go to that function to check what’s populated. My example is as follows:

So, I can see two functions here. One for creating dog and the other for creating human. Nonetheless, this is much more readable than using functions. So, I prefer to let this duplicate code stay as it’s for a while.

Removing duplicate code immediately is a premature optimization. For many cases focusing on just the duplication will make things worse or lead to complex code. It’s wiser to try to keep your code clean and tested. At some point, there will be a refactoring opportunity to remove duplicates. Let’s see the example for this.

In the example, one can create a function for overachieving salary. Moreover, once can create overtime salary by calling simple salary. Nevertheless, I think it’s early. We can still tolerate this for a while. I like code base to mature a little bit. Note that we have tests in place to ensure these two functions work correctly. Let’s see how this might evolve. We’ll add another function to calculate salary after tax. I think this is the moment to do the refactor.

In consequence, I think we can live with duplicate code for a while and maybe more. Granted duplicate code is against design principles but these principles aren’t really the goal. Our goal is to deliver maintainable and understandable code. We should allow some time for duplicate code to mature.

One Comment

  1. Joe Joe

    true, duplicate code isn’t bad, especially if you’re at first trying to make things work rather than make things pretty

Leave a Reply

Your email address will not be published. Required fields are marked *