
Sugar-like series (II)
It’s good, tempting, it comes instantly, but on a long run it will most probably cause some issues. What are the similarities when it comes to building applications?
Copy-pasting code
So, the requirement is clear-enough so that can be coded.
Other project’s sources or some stackoverflow.com snippets seem to be the perfect solution and ready to be integrated with the rest of the codebase.
The problem I see with this approach is that the code being copy-pasted is at most the best version of what a developer could think of at a given point in time, in a given context, for a given problem.
Even if the problem to solve is identical, better options could be currently available:
-
Language improvements (e.g. using a lambda expression instead of an anonymous instance when creating a Comparator)
-
API improvements (e.g. using List.of() instead of a custom method for creating a constant list)
-
Dependencies improvements: libraries used by the copied code could no longer be needed, as similar features are now available in the JDK (e.g. benefit from the Stream API instead of depending on guava)
-
By not considering these concerns, the code will inherit the technical debt of the one being copied.
Even if the code is pretty recent and technical debt free, the coding style might not fit the one of the codebase being developed or the requirements related to quality (e.g. Sonar rules).
But it could also be the case that the problem is just similar, but not identical.
It can be simpler, which makes the inserted code over-complex. For instance, the desired return value of a method can be a just a Collection – it doesn’t need to be a List, as ordering doesn’t matter.
It can have different requirements when it comes to validation. Maybe the copied code is considered safe, as it’s intended to be used only internally, while the desired code is intended to be called from the outside world (e.g. from a REST endpoint).
The differences can be so subtle that can only be identified during the testing phases.
Unit tests
There is also a series of things to question when it comes to unit tests and which might signal some red flags if the answer is ‘No’:
- Is the copied code covered by unit tests?
- If it does, are they going to get copied as well?
- Do they still make sense for the functionality being developed?
With all that in mind, when it comes to writing code for solving a problem that cannot benefit from using a library or a service or any sort of reusable software component, I find it way cleaner and in the end easier to just write code from scratch, rather than copying code and making all sort of adjustments in order to make it fit the functional, coding style & quality and testing coverage requirements.