Refactoring

Refactoring is the process of changing code to make it cleaner, while preserving its behavior.

To be able to refactor properly, automated tests are needed. Without automated tests, changing the code is a risky endeavor, since it is more difficult to know whether something broke due to the change.

Automated tests also encourage smaller changes, as those are less likely to break any existing tests. Unless functionality is moved from one function to another, refactoring should not require any changes in tests, as it shouldn’t change functionality.

Some refactorings might have an impact on performance, meaning that the actual instructions executed by the computer do change. However, this kind of behavioral change is okay in refactoring, as long as it improves the situation (better performance, much more maintainable code) and doesn’t negatively impact another criterion too much.

1 Step-by-Step

  1. Identify a small change you want to do
  2. Ensure there’s tests for the part of the code you want to change
  3. Ensure the tests are succeeding
  4. Make the small change
  5. Check whether the tests are still succeeding
    • if yes, continue with (6)
    • if no: fix implementation or undo change and try again
  6. If you want to change more, go to 1; otherwise stop

You should also regularly commit your code if you’re using version control (which you should). Good places to do this are after step (2) if there was a change, and after step (5).

2 Backlinks   backlinks