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
