WHY REFACTOR?

When practicing TDD, the goal when initially writing a method or creating a class is to simply make the test pass and nothing more. At this point you're not necessarily looking for style points or to make your code reusable or elegant. You're simply trying to make the tests “all green,” meaning that the tests all pass. Once you've accomplished this, the next step is to improve your code. In practice this is a very practical approach. Many developers spend too much time trying to make their code elegant and beautiful the first time through. They end up missing some important pieces of business functionality that they then have to somehow work into their code. By starting from a point of complete business functionality before making your code beautiful, you ensure that the top priority — working business code — is met before anything else. Unit tests help you make sure that no matter what you change in the name of refactoring, your code still meets the business need. This is the genesis of the term fearless refactoring.

A Project's Lifecycle

TDD involves a lot of new concepts for many developers, such as mocking and dependency injection (covered in Chapter 5). These are relatively simple to understand and to get comfortable with compared to one of the major (if not the prime) tenets of TDD: Write a test before you write your code. The idea behind TDD (remember, the first D stands for driven) is that your tests become living, breathing executable versions of your business ...

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.