Oct
11
TDD may be a way to derive algorithmms from first principles (excerpt from Uncle Bob's Echoes From The Stone Age)
Here is a classic example. Imagine you were going to write a sort algorithm test first:
- Test 1: Sort an empty array. Solution: Return the input array.
- Test 2: Sort an array with one element. Solution: Return the input array.
- Test 3: Sort an array with two elements. Solution: Compare the two elements and swap if out of order. Return the result.
- Test 4: Sort an array with three elements. Solution: Compare the first two and swap if out of order. Compare the second two and swap if out of order. Compare the first two again and swap if out of order. Return the result.
- Test 5: Sort an array with four elements. Solution: Put the compare and swap operations into a nested loop. Return the result.
The end result is a bubble sort. The algorithm virtually self assembles. If you had never heard of a bubble sort before, this simple set of tests would have driven you to implement it naturally.
Problems like Bowling, Prime Factors, and Bubble Sort hold out the interesting promise that TDD may be a way to derive algorithmms from first principles!
