CODE SMELLS

Again, no code is perfect. This is a fact of life. But developers who practice TDD still strive to make their code as good as possible. A key skill to help you do that is the ability to evaluate code and to quickly and easily identify common potential trouble spots without having to run the application. These common problems are called code smells.

What Is a Code Smell?

Over the many years that applications have been developed, developers have always needed to solve a common recurring series of problems in code. These problems eventually found a series of common, widely known, widely used solutions. These solutions became known as patterns. As a corollary, over the many years that applications have been developed, developers have always made many common recurring mistakes. These mistakes, and the problems they tend to cause, are called antipatterns. Code smells are simply a collection of commonly known and widely found code-based antipatterns. This section demonstrates a few of the more common code smells. The next section focuses on some common steps to correct them.

Duplicate Code and Similar Classes

Consider the following code:

public class WidgetService
{
    private const double PricePerWidget = 1.5;
          
    public double GetQuoteForWidgets(int quantity)
    {
        return PricePerWidget*quantity;
    }
          
    public string PlaceOrderForWidgets(int quantity)
    {
        var invoice = new Invoice
                          {
                              TotalPrice = PricePerWidget*quantity
                          };
        return invoice.InvoiceNumber;
    }
}

This simple WidgetService provides ...

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.