The other day, Uncle Bob Martin wrote an interesting blog about estimation. The problem he used as an example was a simple line break algorithm. The typical way of implementing something like that withTDD involves building up your solution in small steps, maintaining state variables to keep track of where you are as you traverse the text. I'm pretty sure that maintaining indices as state is a major cause of grief as people move toward a solution, so I started wondering.. what would a pure functional solution to this problem look like and would you get to it in small steps?
Here's what I ended up with:
If you don't know Haskell, this is sure to seem cryptic. In a later blog, I'll explain how it works and I got to it.
No doubt other Haskellers will chime in and offer more direct solutions, but the code above does solve the problem, and the fact of the matter is that I did not use TDD to arrive at it. At least not the TDD where 'T' stands for "Test." Instead, I drove the design using type signatures. It's actually a very nice design technique. You start with the type signature of the function that you want to write to solve your problem (in this case lineBreak) and you drill down, refining type signatures for the functions that you need to make the original function work, keeping an eye out for functions which already exist.
This may seem to be plain old top-down structured design, but I think there are some differences. For one, it seems easier to see things as a linear flow of transformations rather than a tree of invocations. I'm still not sure whether that is a real distinction.
Oh, and the estimation? The design took longer than I expected, but that's par for the course, isn't it?