Chapter 1 of Fowler, Refactoring: Improving the Design of Existing Code (Addison Wesley 2000) presents an extended example of refactoring, which covers pages 1 to 52 of the book. The example demonstrates the process of refactoring and several specific refactorings that one typically encounters in the process of refactoring code. The example, as presented in the book, is written in Java. This project, and its related projects, translate the example to C#.
How the Example Was Translated
The C# example project follows Fowler's code fairly closely. Changes and additions to Fowler's code are as follows:
- I used C# properties in place of Fowler's public accessor methods (getter/setter methods).
- Fowler declares his price codes as Java constants. I have declared them as a C#
- Unit tests have been added to the example, in a class named Tests.cs. All test classes and methods were created to the specifications of NUnit v. 2.0.
Using the Example
The source code file contains a VS.NET project titled "StartingPoint". This project represents the initial state of the project, before any refactoring has been done. It appears on pages 2 - 5 of the book.
Use this code as your starting point to work through the chapter. As Fowler performs each refactoring in the book, follow along, performing the same refactoring on the C# project. This process will help you gain a better understanding of what Fowler calls the "rhythm of refactoring", as well as the specific refactorings demonstrated in the example.
Testing As You Go
Unit testing is a key element of refactoring. A good suite of unit tests allows you to make a small change, then test. Make another small change, then test again. Once the tests are written, unit testing with a tool such as NUnit or csUnit is nearly automatic and instantaneous.
Fowler mentions his tests in Chapter 1 of Refactoring, but he doesn't show them. So, I added a simple suite of unit tests to the C# project to test the basic elements of the example. I don't claim these tests are complete; merely adequate. They are written for NUnit 2.0, and the project contains a reference to the NUnit framework DLL.
The project requires that you have NUnit installed on your computer. NUnit can be downloaded from NUnit website. The project reference assumes that the DLL can be found in its default location. If it cannot be found, then you should delete the existing reference and add a new one that points to the correct location.
I hope you find the example as useful as I did. It helped me understand why refactoring (and testing) are core disciplines that every programmer should exercise in writing code.