Four Tips To Keep Refactoring Efficient

We all write elegant code the first time that never needs to be changed, right? Me neither.

Refactoring is just another tool in the developer’s belt. It wasn’t until recently that I realized how important a tool it is. I started a small refactor that turned into a big refactor that turned into an enormous refactor. In the end, I felt great about the new architecture, but it ended up being a lot more work than I anticipated. Coming out of that experience, I have four tips for keeping your refactors efficient and manageable.

1. Have Good Test Coverage

All production code should have good test coverage. When you get into a refactor, your test coverage can be a life saver. Tests are like a developer’s instruction manual for your system. They describe the rules of the system and how all of the parts fit together. When you’re refactoring, you are not (typically) changing those rules. You know your refactor is complete when your all of your tests are green.

2. Refactor on A Main Branch

Sometimes, you get into a feature and realize that another part of the system will have to change in order to play nicely with this new feature. If you have the foresight to make this connection, you can save yourself a lot of time. Instead of making the change on your feature branch, do it on your develop branch. Now, you’re starting off with a green test suite. Leveraging that will give you a great indicator of when your refactor is complete.

3. Keep Tests Green Often

Have I mentioned that tests are important when refactoring? If you’re starting a refactor, make the smallest changes you can while trying to keep the tests green. If you need to abstract some code into a new helper, do only that and wait for a green test suite before advancing. Refactors can become overwhelming when you’re in the middle of them, all of your tests are red, and you have no idea why.

4. Remember Your Purpose

In my recent experience, I quickly forgot my purpose and only saw more code that needed refactoring. I kept biting off more and more until I had a big mess on my hands. I could have significantly cut down the time of the refactor if I had more discipline in staying with the original refactor. It’s like when you decide to take the trash out and end up cleaning your entire house. It’s not a bad thing that my entire house is clean, but I could have accomplished what I set out to do in much less time than it took to clean the whole house. Remember why you started this refactor, and stay committed to that.

Refactoring is a common task for developers. Don’t be scared of it. You need to refactor because assumptions change, specifications change, and you know more about the system now than you did when you wrote the original code. Just remember to keep your refactors disciplined and that tests are your friend, and you will be just fine!