Refactoring – changes made to a piece of code to make it easier to understand and easier to modify without affecting the observable behaviour (meaning it should do the same things it did before refactoring).
Refactoring doesn’t mean cleaning up the code. It is a combination of small steps that won’t leave the code too much time in a broken state. Refactoring can be a part of a code « restructuring ». While developing you can realise that would be much easier if the code were structured differently.
Refactoring is a valuable tool that can be used for several purposes. It is not the answer to all problems.
Regular refactoring helps keep the code in shape and improves the design of software. It make the code easier to understand for the next developer which might be you. If you don’t want/can remember all the things you write, write your code in a way it will help you remember.
Refactoring can help finding bugs because when clarifying the structure of a program you can spot a lot more easier bugs.
Refactoring helps you write code faster because you can leverage the existing things and you can quickly build on what’s already there. Also, if the code is clear, you will know what subset you have to change and you are less likely to introduce a bug.
When?
You can refactor before adding a new feature, preparatory refactoring.
Understand what the code does, comprehension refactoring. Move the understanding of the code from your head to the code.
Refactoring is a part of programming.
There are cases when the refactoring efforts can take weeks to complete. A useful strategy is to agree to gradually work on the problem over the course of time and not having a team dedicated to refactoring.
Refactoring during a code review would be better with having the original author of the code present because he can provide context on the code and fully appreciate the reviewers’ intentions (code review + pair programming).
Don’t refactor when it’s easier to rewrite than to refactor it.