When is code duplication better than reusable
When writing code you should be thinking about making your code reusable. It is part of every good programmer’s toolbox. After all, it can save a ton of time on maintenance. But it does come at a cost. There are times where you should strive for making your code as reusable and generic as possible. There are also times where, well, maybe you should just do the old copy and paste. When do you prefer one over the other? Let’s dig into it.
I want to start by making a very important note, you will probably never always get it right. Why? You don’t have a crystal ball and can predict the future. You will see what I mean at the end.
Why do we write reusable code?
The best advice I have ever gotten was from one of my teachers at University, he told me to be as lazy as possible when writing code. That does not mean, don’t write good code or working code or missing requirements or anything like that. It just means; write code that you can easily read and maintain. If you copy and paste your code all over the place, and someone tells you to add or change it, doesn’t it make your life easier just to update it in one spot? Ah sounds magical.
The cost of reusable code
Before you go out and make everything reusable you should know the cost of reusable. If you have experience with making reusable code you probably have dealt with the cost. The cost of time. At least sometimes. If you have some pretty simple logic it can be pretty easy to make code reusable or generic enough.
It is not a good idea to make everything just reusable because you can end up having code that is referenced by a lot of code. This can make it hard to update and if you do, a lot to test. You end up having a heavy cost to adding a line of code because you don’t know if it will break other parts of the system. If you have this code, sometimes it’s a good idea to break it up and make it less generic.
Reusable or not?
So you’re writing some code, do you make it generic? This is where you need a crystal ball. You make it generic when you predict that the code is going to stay the same and not diverge, or at least not very much. The problem is all this is very situational. I can not tell you that when x then do y. This is when experience comes in handy. Do you think the requirements are going to change or update? Could they?