IMPROVING THE CODE BY REFACTORING

When you start writing code using TDD, your only goal is to make the tests pass. Don't worry about writing code that is elegant or functional or pretty. Make sure that you can meet the primary purpose of development: satisfying the needs of the business. The passing tests, which are themselves based on business requirements, indicate that business needs are being met. After the business needs are met, you should think about refactoring.

As stated in Chapter 4, refactoring is the act of improving on existing code to make it more efficient, more readable, and more maintainable without affecting the code's external behavior. Having a suite of passing unit tests allows you to freely refactor your code and know exactly when you've gone beyond the point of having code that satisfies the business. Now is the time to put on your editor hat and take a good, hard look at your code. Is it readable? Can someone new to the team look at your code and quickly understand its function and how the code accomplishes this? Does your code meet the SOLID Principles? Do you have a lot of duplicate code? Are you effectively using interfaces and abstractions? Are your dependencies being injected to keep your coupling loose? Now is the time to address these questions. Work to make your code better, but keep your tests passing.

Get Professional Test-Driven Development with C#: Developing Real World Applications with TDD now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.