Refactoring is a key step in TDD. It involves improving the internal structure of source code while preserving its functionality. Note that in the TDD cycle, refactoring occurs after a test passes. A failing test would require rewriting the code to pass the test. Refactoring shouldn’t be confused with fixing bugs, simply rewriting code, or improving observable aspects of software like the UI.
According to TDD, refactoring should continue until the source code conforms to the simplicity criteria. Developed by Beck, these criteria are intended to determine whether some amount of source code is “simple enough.” These criteria are also known as the rules of simple design and are listed in order of priority:
The source code is verified by automated tests, and all such tests pass.
The code contains no duplication.
The code expresses separately each distinct idea or responsibility.
The code is composed of the minimum number of components (e.g., classes, methods, lines of code) compatible with the first three criteria.