A little copying is better than a new dependency

449 words | 2 minutes to read

Libraries typically take an evolutionary path and grow in functionality over time, and it is often the case that if the library we depend on were decomposed into separate smaller libraries, we might be able to get away with using one or a few of these smaller libraries, as we rarely need to use everything in a library.

Whilst we can’t control the scale and modularity of libraries we depend on, we do have the option to copy the critical parts of a library into our code. This may seem counter-intuitive at first - why would we copy a part of a library when build tools such as Maven and Gradle make it so easy for us to just depend on it?

The answer is that if we can copy a small amount of a library into our code base, we are able to more easily abide by our other best practice of keeping our dependencies minimal. This may seem like a minor victory, but by copying the required code into our code base, we can avoid all of the diamond dependency issues of having an explicit, full-blown dependency in our project.

Is this shading?

Technically this is shading, which goes against the guidance to avoid shading dependencies, so it is important to understand all of these implications. In particular, we have to appreciate that any code we copy into our project will no longer be maintained by the project where the code originated, and so it becomes our burden to keep this updated (if necessary).

When we copy code into our project, we should move the code into a package namespace that we own. This prevents classpath collisions if the library comes onto our classpath through other means, but this also means that we have to be careful when we copy this code into our project that it does not form part of our public API (that is, that it is not exposed through our APIs to end users). This is because we will confuse our users with the existence of equivalently-named APIs in different package namespaces.

Can I copy any code I want?

Libraries are licensed under all manner of license, ranging from commercial to a huge number of open source licenses. It would be extremely unwise to copy any code without first consulting with a lawyer who can review the license of the library code you wish to copy. Some open source licenses can enforce requirements onto your project (such as requiring your code to become open source or requiring attribution). Only your team and your legal advisors can determine if the code you want to copy can be copied.