Working with legacy code can be a chore. But unless you always work on new projects, it's inevitable. Here are some tips on how to make it easier.
Rewrite or refactor?
Almost everyone who starts working with legacy code asks this question. But there is no right or wrong answer. Both methods have their place, and you always have to consider your situation. Rewriting a piece of software is usually more expensive and time-consuming, but even then, it can still make sense. If your application is currently a monolith, and you are trying to move towards microservices, it makes a sense to rewrite that piece from the start. Trying to adapt existing monolithic code into a microservice can be a massive challenge and it might take a lot of unnecessary work. At the same time, refactoring is usually a much safer option. A complete rewrite can easily introduce new bugs or omit hidden functionality by mistake.
Tests are your friends
Legacy code often comes with a lack of proper tests and documentation. And that's where you have to start. No matter whether you choose to rewrite or refactor, you should always start with tests. They will be your guidelines, and if correctly written, should assure you that the functionality is working as expected. This part can be tough because without any documentation or previous tests you can never be sure that you covered every possible test case.
Fill in the docs
The documentation is one of the most important aspects of software development for every company. Unfortunately, many developers forget about properly documenting the code that they write. When attempting to refactor or rewrite, always remember to keep documentation in mind. It doesn't take much time to write, but it will help every developer who has to work with your code in the future.
Replace deprecated dependencies
Unused dependencies are like junk. At some point, if you don't remove them, your project will grow in size a lot and they will lead to a lot of "code smells". Deprecated dependencies can cause conflicts, incompatibilities or even crashes in the future. In some cases, dependencies could even lead to security vulnerabilities. This is also why I always recommend keeping as up-to-date with packages as possible.
Dealing with legacy code is not an easy task, but it can be a great learning opportunity. I believe that bad legacy code can teach new developers the importance of creating proper documentation, as well as testing their code.