Refactoring is the process of changing code to be different without changing the external functionality. It is very important that you do not change functionality and refactor code at the same time. Doing both at the same time makes it more likely that you will introduce bugs. Having a means of testing, either UI or unit testing, to verify that functionality has not changed makes refactoring less likely to introduce problems..in other words, easier!
Refactoring code should be done often and at all stages of the development lifecycle. If you write a new code, you should refactor it afterwards. If you change some functionality, you should refactor afterwards. If you changed some aspect of the code, you may want or need to refactor some other parts of the code. If you have a file that has not been touched in a long time it may need to be refactored. While many of my examples suggest refactoring code after other changes are made, sometimes you may need to refactor code before you add or change functionality.
The two most important aspects of refactoring are:
The primary reason for refactoring is to update the code to be simpler. Simple code is more readable, maintainable, and often more efficient. In some cases, you will refactor before adding functionality to make adding that functionality easier.
How you go about refactoring is a simple process of testing the current functionality, changing the code, and testing again to verify that the functionality has not changed. You then repeat that process as often as required to reach the goal you set out for when you started. To prevent problems, it is best to refactor the code in a single way and verify after each change. Doing small changes will make it easier to identify the change that altered the functionality.
The tests you need do not have to be elaborate, or even automated. Tests can be as simple as a written set of steps to follow, along with notes of the expected behavior. Unit tests that you can run manually or automated tests are better and useful for future development. Automated UI tests are also very good. Often a combination will yield the best results overall. Don’t be intimidated about testing being hard or ignore the tests altogether. You can start simple and build up over time.
When you are refactoring, always make discreet and small changes then verify. Updating a variable name, changing spacing, standard code formatting, or a conditional statement — these should all be done separately so you know what change you just made if there is a problem when you verify.