There are two main reasons to refactor.
- To improve the code/design before building on it’s top: It’s really hard to come up with good code on the first attempt. The first try to implement any initial design will show us that we misinterpreted or forgot some logic.
- To adapt to changes in the requirements. Change happens in the software development; to be responsive to change is better to have a good code base.
We have two options for both scenarios, path the code or refactor it. Patching the code will lead us to unmaintainable code, and will increase our technical debt, it’s always better to refactor.
The sooner the better as is easier, faster and less risky to refactor over a recently refactored code rather than waiting to refactor for the code to be almost completed.
All the code and all the design are candidates for refactoring. An exception for not refactoring something could be a working piece of code which is quality is low, but due to be close to a deadline, we prefer to keep our technical debt rather than risking the planification.
There are two rules to never be broken when refactoring
- With lots of unit tests. This is going to give confidence to the developer that he is not breaking anything during the refactor.
- With consistency. There’s many ways to improve the code, but the underlying direction has to be always the same, for example: if you are always using error codes and not exceptions, keep using error codes… This will make sure that everyone is rowing in the same direction
Two persons should be in charge of the refactor.
- The developer who created the code. He will have the main role of the refactoring, he will perform all the changes.
- A senior developer. To supervise the refactoring, he will mainly keep an eye on consistency.
So, is refactoring good or is it bad?
Refactoring is the essence behind iterative development, but in order to turn it into a good practice you have to be very careful, again, it’s essential to have unit tests, and to refactor with consistency, if you do so refactoring will turn into a very powerful tool for your team.
The main reference about refactoring is the book “Refactoring: Improving the Design of Existing Code” by Martin Fowler, a must read for any software developer. Other references are: