What is Refactoring?

A non-programmer recently asked me what refactoring is. Refactoring is the process of changing a software system in such a way that it does not alter the external behavior of the system, but improves the internal structure of its code, making it easier to understand and maintain, and thereby reducing the cost of making subsequent changes to the system. Refactoring goes hand-in-hand with unit testing. Each unit test, should test a single method for a single set of inputs against an expected result.

  • BEFORE you start refactoring, check that you have a comprehensive set of tests. If there are no tests for the method you are about to change, first write ‘enough’ tests to cover the existing functionality. Tests should have as few external dependencies as possible. The greater the code coverage of the tests, the less the risk of introducing errors.
  • When refactoring, make changes in small steps. If you make a mistake, it is then easier to find the bug (provided you have a comprehensive test suite!).
  • When you need to add a feature to an application, and the application’s code is not structured in a convenient way to add the feature, first refactor the application to make it easy to add the feature, and then (and only then) add it.
  • I cannot over stress the importance of good naming. Never be afraid to change the names of things to improve clarity. If you find yourself unsure of how to name a class, it is probably an indication that you should try and split it into several, smaller classes.

I’m sure everyone has seen code at some point and thought “I should really change that, but I’ll have no way of knowing if my changes will break something else”? I know I have. Unit tests with ‘sufficient’ code coverage give you the courage to make radical code changes.

The unit testing tools you should take a look at are NUnit and NMock as a starting point, and then MbUnit and RhinoMocks. TestDriven.Net is a Visual Studio add-in that enables unit tests to be run from within the IDE. Automating your unit testing can be done using NAnt and
CruiseControl.NET (as well as several other tools including MSBuild). What are you waiting for? Write some tests and get refactoring!