Test-Driven Development

Site Admin · 11 Sep 2026 · 8 views

Test-Driven Development

Red, Green, Refactor

Test-Driven Development (TDD) flips the usual order: write the test before the code. The rhythm is a loop of three stages. Red means write a failing test for behavior that does not exist yet. Green means write the simplest code that makes it pass. Refactor means clean up the code while the test keeps proving behavior.

// 1. RED: write the test first
@Test
void discountAppliesToOrdersAboveTotal() {
    double total = new Checkout().finalTotal(200.0);
    assertEquals(180.0, total, 0.001);
}

The test will not even compile until Checkout and finalTotal exist; that compile failure is your first red. Then implement just enough to pass:

// 2. GREEN
class Checkout {
    double finalTotal(double amount) {
        return amount > 100 ? amount * 0.9 : amount;
    }
}

Why Write the Test First?

Writing the test first forces you to design the API from the caller's perspective: what should the code do, and what is the cleanest way to call it? It also guarantees every line of production code has a reason to exist, because nothing is written without a failing test demanding it.

Baby Steps Compound

Each loop is small, often a few minutes long, but the effect compounds. The suite grows exactly alongside behavior, covering every piece of logic almost for free. Regression becomes rare because the test for new behavior already existed before the behavior did.

The Discomfort Is the Signal

TDD is famously difficult to write badly-shaped code with. If a test demands awkward setup or a huge mock, the design is probably tangled. The friction is feedback about the design, and the fix is usually smaller functions or dependency injection, not more test machinery.

When TDD Feels Right

TDD shines for logic-heavy code: calculations, parsers, validators, and business rules. It is overhead for trivial glue and proofs of concept. Learn the loop on pure logic first, and you will find yourself reaching for it automatically when the stakes rise.

Key Points

  • TDD cycles through red (failing test), green (passing code), refactor.
  • Tests drive the API shape from the caller's viewpoint.
  • Every production line exists because a test demanded it.
  • Test discomfort often signals a design problem, not a testing problem.
  • TDD is most valuable for logic-heavy code.
Share this post:

Comments (0)

Please login or register to comment.