Test-Driven Development: The Red, Green, Refactor Cycle
Test-Driven Development (TDD) flips the script: you write a failing test *before* the feature code. This 'Red, Green, Refactor' cycle ensures every piece of code is testable. It's common in agile for building robust features.
THE MENTAL MODEL: Test-Driven Development is a development discipline, not just a testing strategy. It uses tests to drive the design of your code. Instead of writing code and then figuring out how to test it, you define the desired behavior with a test first. This forces you to write code that is inherently testable and focused on a single responsibility. The mantra is "Red, Green, Refactor."
HOW IT WORKS: The TDD cycle has three distinct steps, repeated for every small piece of functionality. First, the "Red" phase: Write an automated unit test for a new feature. Since the code doesn't exist yet, this test must fail. A failing test proves that the test is working correctly. Second, the "Green" phase: Write the absolute minimum amount of production code required to make the test pass. The goal is not elegance, but simply to pass the test. Third, the "Refactor" phase: With a passing test as a safety net, you can now clean up the code you just wrote. Improve its structure, remove duplication, and enhance clarity in both the production code and the test code, all while ensuring the test continues to pass.
WHEN TO USE IT: TDD is most effective when building systems where correctness and long-term maintainability are critical. It provides a regression safety net, making it easier to add new features or refactor complex logic without introducing bugs. It's a foundational practice in many agile and Extreme Programming (XP) environments.
WHEN NOT TO USE IT: TDD can feel slow for purely exploratory or prototype work where the final requirements are unknown and likely to change drastically. It's also less applicable for code that is difficult to unit test in isolation, such as complex user interfaces or integrations with legacy systems that lack clear APIs.
ONE CANONICAL EXAMPLE: Imagine adding a sum(a, b) function. Red: Write a test that asserts sum(1, 2) equals 3. Run it; it fails because the function doesn't exist. Green: Create the function: def sum(a, b): return 3. The test now passes, but the code is too specific. Refactor: Change the implementation to def sum(a, b): return a + b. The test still passes, but the code is now correct and general. Now, add another test for negative numbers and repeat the cycle.
Read the original → en.wikipedia.org
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.