Refactoring - How?

In my previous post, we established that the need to refactor may arise from different situations. Once you are sure refactoring is in order, you should first make sure the rest of your team knows about the ref you are going to do.

This short series of blogposts answers the “why”, “how” and “when” of code refactoring.
If you are...
- a manager or client of a dev team who needs to understand why your team wants to spend time on things that don’t show immediately tangible results
- a developer who needs to explain to a manager or client why you need to spend time on something with non-tangible results. ...then this blog post was made just for you!
How Do I Do It?
In my previous post, we established that the need to refactor may arise from different situations. Once you are sure refactoring is in order, you should first make sure the rest of your team knows about the ref you are going to do.
If you are using task tracking tool like JIRA, the refactoring task should go there too, as a normal part of the iteration. It’s good practice to describe exactly what value it will bring, and identify the parts of code repository you are going to change.
After that, the recipe is simple:
- write a test for the part of code you want to change (if there isn’t one already)
- break the code intentionally (make sure the test is failing)
- rewrite the code
- make sure the tests is green
The Big Ref
So the above situation is overly simple. The truth is that it can only applied to small refactorings that take less than a day. What about the ‘big ref’ scenario? For instance, what if you want to change the version of rails for your project?
Big refactoring tasks should be split into smaller tasks—there’s no other way around it. No sane project manager will accept a refactor request that will block a developer for a week or two! And it’s understandable from a business perspective, right?
It’s the developer's responsibility to make sure the change can be done in small steps. Need inspiration? Check out how Newrelic changed its wheels while driving 80mph.
Even large refactoring tasks can be fragmented into small parts – just plan ahead and don’t jump on it all at once.
The Ugly Refactor
Remember that good refactoring relies on proper preparation and writing tests first. In many cases, developers will throw themselves on refactoring just because they think something ‘looks ugly’. That’s never a good enough reason to spend time on reworking it, and often leads to conflicts with management.
By planning your future steps and creating tests, you’ll reach a point where the data validates the idea. After all, “Refactoring without tests is just changing stuff“, as the saying goes.
In our next blogposts, we take on the “when” of refactoring - stay tuned!