DEV Community

Rajat Saxena
Rajat Saxena

Posted on

Effective Refactoring

When you start working on some existing code, sooner or later you are going to bump into a situation where you have to refactor some part of that code. There can be many motivations behind that refactor. Maybe the code is too complex to maintain, maybe the code is doing just way too much and so on. So here are some quick tips regarding refactoring that code effectively.

1. Write unit tests
Before you even think about changing that code, you have to make sure that you have written all the unit tests you need in order to refactor that code. These tests will ensure that you've refactored the code while maintaining the existing behaviour and you've not introduced new bugs while changing the code. Make sure you've written test cases to cover all branches (if-else, switch etc.) of the code.

2. Break it down
If the code in question is doing too many tasks i.e. fetching data, parsing data, doing computation on it, transforming the result etc., you need to break this code into several functions each doing a single task. This way you'll make your refactor more complaint to the notion of the single responsibility principle. Make sure you also write some more unit tests to test these new functions as well.

3. Touch base with original author(s)
If you have the original authors of that code still around, you can ask them to review your code. It is much easier for them to recall the intricate details about that code and scenarios they handled. They may tell you about some additional scenarios you should have considered while refactoring. Make them the reviewer of the PR for this refactor or get in touch with them in person, whatever floats your boat. If the original author(s) are not around, you can still ask other developers to review your refactored code so as to weed out code smells and things that look off.

That's it for today. I build CourseLit and teach software development on YouTube.

Top comments (0)