Interview frequency: …
Short answer
First write a small test that fails (Red), then write the minimum code needed to pass (Green), and finally improve and clean up the code while ensuring the test still passes (Refactor).
Explanation
TDD's main benefit is not merely finding bugs; it is an engineering design feedback tool. Writing the test first forces you to think like a user of the API rather than its creator, resulting in intuitive, easy-to-use interfaces and naturally decoupled, testable modules.
Code example
# 1. RED — write a failing test first
def test_fizzbuzz():
assert fizzbuzz(3) == "Fizz"
assert fizzbuzz(5) == "Buzz"
assert fizzbuzz(15) == "FizzBuzz"
assert fizzbuzz(7) == "7"
# 2. GREEN — the simplest code that makes it pass
def fizzbuzz(n: int) -> str:
if n % 15 == 0:
return "FizzBuzz"
if n % 3 == 0:
return "Fizz"
if n % 5 == 0:
return "Buzz"
return str(n)
# 3. REFACTOR — improve names and structure while the tests stay greenCommon mistakes
- Skipping Refactor after a test passes (Green) and moving to the next task, leaving quick patches in the code and accumulating technical debt.