Example-driven development tutorial
TL;DR
We motivate the need for Example-Driven Development (EDD) as a means to eliminate guesswork in classical TDD, by focusing on exploring examples rather than writing tests that must turn green.
We introduce a design problem of modeling prices for goods, and then embark on a series of exercises to develop the price domain model classes using EDD.
Motivation
With Test-Driven Development (TDD), you develop code by incrementally adding a test for a new feature, which fails. Then you write the “simplest code” that passes the new test. You add new tests, refactoring as needed, until you have fully covered everything that the new feature should fulfil, as specified by the tests.
This is fine, but begs several questions:
Where do tests come from? When we write a test, we must “guess first” to imagine what we want to create (setup) and test (assertions).
How do we write the simplest code that passes? A failing test gives you a debugger context, but then what? You have to navigate somewhere else to add some missing classes or methods, navigate back to the test, and so on.
What use is a green test? Green tests can be used to detect regressions, but otherwise they don't help you much to create new tests or explore the running system.
Example-Driven Development (EDD) is intended to address these issues.
Examples are just like tests, except they also return an object (an “example”) that can be explored, or used as a setup for another test (example). This leads to a hierarchy of examples, thus eliminating duplicated code in test setups (a common problem), and reducing the number of failing tests.
However the key differences to TDD are in the process. Instead of starting by writing a test, you start by writing some code that creates a domain object. You then incrementally extract examples from this code, exercise the objects and extract assertions .
In other words, instead of starting with the tests, the tests (examples) emerge from an exploration process. It's almost the same, but also fundamentally different in that examples emerge from an exploration process, not from guesswork.
EDD is especially effective in a live programming environment in which you can explore and update live objects.
The following exercises will guide you through an EDD process for modeling prices for goods.
Modeling Prices — initial requirements
The following minimal requirements will guide us in the exercises:
A price can be something like 100 EUR. Prices can be added or multiplied. A price can also be discounted either by a fixed amount of money, or by a percentage. All operations can be combined arbitrarily. And for audit purposes, we want to track all operations that lead to a concrete amount of money.