Applying TDD to a Real Feature
Consider building a shopping-cart discount calculator: apply 10% off when the cart subtotal exceeds $100, otherwise no discount. Rather than writing the whole function up front, TDD breaks this into a sequence of small, verifiable steps, each adding one new fact about the required behavior. You start with the simplest possible scenario, get it passing, then add the next scenario that the current implementation cannot yet handle, letting the design emerge from the accumulated test cases rather than from upfront speculation.
Cricket analogy: A batting coach builds a player's technique against short-pitched bowling one drill at a time — first balance, then the pull shot, then timing against 140kph — rather than throwing a full match scenario on day one, just as TDD builds the discount feature scenario by scenario.
Step One: The First Failing Test
The first test should cover the case with no discount, since it is the simplest branch of the requirement: applyDiscount(50) should return 50 unchanged. This test will fail initially because applyDiscount does not exist, which is expected and correct. The minimal implementation to pass it is simply return subtotal — no conditional logic is needed yet, because no test has demanded it. This might feel like cheating, but it is the discipline: never write code the tests do not yet require.
Cricket analogy: A net session starts with a bowling machine set to a gentle, predictable line just to confirm the batter's stance and bat swing work at all, before any spin or pace variation is introduced, just as the no-discount case checks the function exists before adding branching logic.
# Step 1: RED
def test_no_discount_below_threshold():
assert apply_discount(50) == 50 # NameError: apply_discount is not defined
# Step 2: GREEN — simplest possible implementation
def apply_discount(subtotal):
return subtotal
# Step 3: RED again — new scenario the current code can't handle
def test_ten_percent_discount_above_threshold():
assert apply_discount(150) == 135.0 # fails: still returns 150
# Step 4: GREEN — generalize just enough to satisfy both tests
def apply_discount(subtotal):
if subtotal > 100:
return subtotal * 0.9
return subtotalStep Two: Triangulating Additional Cases
With the threshold branch added, further test cases sharpen the boundary: what happens exactly at $100 — is the discount inclusive or exclusive of the threshold? A test like apply_discount(100) == 100 forces the condition to be subtotal > 100 rather than >=, closing an ambiguity the requirements might not have stated explicitly. Each new test either exposes a gap in the current implementation or confirms existing behavior, and both outcomes are valuable: the former drives new code, the latter documents an intentional decision.
Cricket analogy: The third umpire checking a run-out at the crease needs a case exactly on the line, not just clearly in or clearly out, to confirm the decision system handles boundary frames correctly, just as testing exactly $100 clarifies the threshold's inclusivity.
Boundary tests (exactly at a threshold, one unit above, one unit below) are among the highest-value tests you can write, because off-by-one errors in conditionals are one of the most common real-world bug sources.
Step Three: Refactor Once Green
Once all scenarios pass, refactor for clarity without changing behavior: extract the magic numbers 100 and 0.9 into named constants like DISCOUNT_THRESHOLD and DISCOUNT_RATE, and consider whether the function name still communicates intent. Because the test suite already covers the no-discount, above-threshold, and boundary cases, you can make these structural changes with confidence — if a refactor accidentally breaks behavior, a test will fail immediately. This is the payoff of the earlier discipline: refactoring stops being a leap of faith and becomes a checked operation.
Cricket analogy: A team re-arranging its batting order after a winning tournament run does so carefully, trusting the season's results as a safety net that will show immediately if the new order underperforms, just as tests catch a bad refactor.
Never add new behavior during the refactor step. If you notice a missing case while refactoring, write it down, finish the refactor with tests green, then start a fresh red-green cycle for the new behavior.
- Break a feature into a sequence of small scenarios rather than designing the whole implementation upfront.
- Start with the simplest scenario and write only enough code to pass it.
- Each new test should either expose a gap in the current code or confirm intended behavior.
- Boundary cases (exactly at a threshold) are high-value tests that catch off-by-one errors.
- Refactor only once all tests are green, and keep behavior unchanged during refactoring.
- Extract magic numbers and improve naming once the safety net of passing tests exists.
- Never add new behavior during a refactor step — capture it as a new test instead.
Practice what you learned
1. What is the correct first test to write for a discount feature with a $100 threshold?
2. Why is a boundary test at exactly the threshold value (e.g., subtotal == 100) valuable?
3. What should you do if you notice a missing test case while refactoring?
4. Why is it acceptable for the first implementation of apply_discount to simply return the input unchanged?
5. What is the main benefit of refactoring only after tests are green?
Was this page helpful?
You May Also Like
Writing Your First Test First
Learn what it means to specify behavior with a failing test before any implementation exists, and how to pick a good starting test case.
Refactoring Safely with Tests
Understand why a solid test suite is what makes structural code changes safe, and how to build one for legacy code that has none.
Common TDD Pitfalls
Recognize the most frequent ways teams misapply TDD — testing internals, skipping red, and overmocking — and how to avoid each.
Related Reading
Related Study Notes in Software Engineering
Browse all study notesMicroservices Study Notes
Software Architecture · 30 topics
Software EngineeringDesign Patterns Study Notes
Software Design · 30 topics
Software EngineeringSoftware Engineering Study Notes
Python · 40 topics
Software EngineeringGit & Version Control Study Notes
Bash · 40 topics
Software EngineeringSystem Design Study Notes
Architecture · 40 topics