liveBook · Manning

Code pollution

As explained in Unit Testing Principles, Practices, and Patterns

Code pollution is the addition of production-code elements whose primary purpose is to enable or simplify testing rather than implement application behavior.

Code pollution adds production code whose only purpose is to enable or simplify testing. It mixes testing concerns into application behavior and raises production maintenance costs. section 11.4

Recognize and replace common forms of pollution:

  • Avoid Boolean environment switches that create test-only execution paths. section 11.4
  • Prefer a small interface with separate production and fake implementations when substitution is necessary. section 11.4
  • Treat interfaces as a less damaging compromise: they add no executable behavior and cannot accidentally invoke test-only paths. section 11.4
  • Do not expose private state or methods merely to make tests easier; verify behavior through the same interface as production code. section 11.8

Replacing a logger switch

A Logger(bool isTestEnvironment) silently skips logging during tests, forcing production code to understand test configuration. Injecting ILogger instead lets Logger remain production-focused while FakeLogger supplies the test behavior. section 11.4

Listing 11.8. Logger with a Boolean switch
public class Logger
{
    private readonly bool _isTestEnvironment;

    public Logger(bool isTestEnvironment)      #1
    {
        _isTestEnvironment = isTestEnvironment;
    }

    public void Log(string text)
    {
        if (_isTestEnvironment)                #1
            return;

        /* Log the text */
    }
}

public class Controller
{
    public void SomeMethod(Logger logger)
    {
        logger.Log("SomeMethod is called");
    }
}

Inspect the Boolean-switch design that creates a test-only branch inside production logging. section 11.4

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Defines the anti-pattern, demonstrates a logger switch, and refactors it through interface-based substitution.
Examples
Uses a Boolean-controlled Logger, ILogger with FakeLogger, helper assertions, and a Comment value-object comparison.
What you can do after
Refactor test-only branches toward separated implementations and keep tests interacting with production code without special privileges.
How it connects
Connects code pollution with dependency injection, test doubles, black-box testing, value objects, and implementation-detail coupling.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Unit Testing Principles, Practices, and Patterns. The section links point to the parts of the book it draws on.