In this lesson, you will learn how to shift your development mindset by adopting the "Red-Green-Refactor" cycle to ensure your code is correct by design from the very first line.
The Red-Green-Refactor Cycle
Most programmers write code first and add tests later. Test-Driven Development (TDD) flips this entirely. You treat your tests as the primary specification for your code, ensuring that you only write what is absolutely necessary.
The cycle works in three precise steps:
- Red: Write a test for a tiny piece of functionality that doesn't exist yet. Run it, and watch it fail (the "Red" phase). If it doesn't fail, your test might be wrong!
- Green: Write just enough code to make that specific test pass. Do not write extra logic for features you haven't tested yet.
- Refactor: Now that your tests are passing ("Green"), clean up your code. Improve the variable names or logic efficiency, knowing that if you break anything, your test will immediately turn red again.
A Practical Example
Imagine you need a function to calculate a discount. Instead of writing the function, you write the test first:
# The "Red" Phase: Write the test before the function
def test_apply_discount():
assert apply_discount(100, 0.1) == 90
# This would fail because apply_discount is not defined.
Next, you move to the "Green" phase by writing the minimal implementation:
def apply_discount(price, discount):
return price - (price * discount)
Now, the test passes. Finally, you enter the "Refactor" phase, where you might optimize the function, confident that your test guards against regressions.
Why This Philosophy Works
By forcing yourself to write the test first, you are forced to consider how your code will be used before you decide how it is built. This leads to cleaner, more modular APIs because you are thinking like an external consumer of your own library rather than an internal implementer. It removes the guesswork from debugging; if a test fails, you know exactly which change caused the breakage.
Key Takeaway: Never write a line of functional code without first writing a failing test that justifies its existence.