When you do something for the first time, you are just doing it to get done.
When you do something similar for the second time, you cringe at having to repeat but do the same thing anyway.
When you do something for the third time, you start refactoring.
When Adding a new Feature
Refactoring helps to understand other people’s code. If it becomes necessary to add a feature to unclear code, refactoring it makes things obvious for you and those coming after you.
Refactoring makes it easier to add features. New features are added more smoothly and with less effort.
When fixing a bug
Bugs resemble cockroaches: they love to live in the darkest, mustiest places of your code. Clean up your code and the errors will practically find themselves.
Managers appreciate proactive refactoring, since it eliminates the need to create special refactoring tasks later. Happy bosses mean happy programmers!
When reviewing code
Review may be your last chance to tidy up your code before it becomes available to the public.
The best way to review is together with the author of the code. You propose changes and decide, together with the author, how difficult it will be to implement various refactoring techniques. Small changes can be made right on the spot.
And how it is done?
Refactoring is best performed as a series of minor changes. Each change improves the existing code slightly while keeping it in functional condition.
Three key components of correct refactoring:
No new functionality is created during refactoring.
All existing tests should be successfully passed after refactoring.