O'Reilly logo

Professional Test-Driven Development with C#: Developing Real World Applications with TDD by Jeff McWherter, James Bender

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required