TDD API – How to Get Initial API Right Using TDD?

tdd

This might be a rather silly question as I am at my first attempts at TDD. I loved the sense of confidence it brings and generally better structure of my code but when I started to apply it on something bigger than one-class toy examples, I ran into difficulties.

Suppose, you are writing a library of sorts. You know what it has to do, you know a general way of how it is supposed to be implemented (architecture wise), but you keep "discovering" that you need to make changes to your public API as you code. Perhaps you need to transform this private method into strategy pattern (and now need to pass a mocked strategy in your tests), perhaps you misplaced a responsibility here and there and split an existing class.

When you are improving upon existing code, TDD seems a really good fit, but when you are writing everything from scratch, the API you write tests for is a bit "blurry" unless you do a big design up front. What do you do when you already have 30 tests on the method that had its signature (and for that part, behavior) changed? That is a lot of tests to change once they add up.

Best Answer

What you call "big design up front" I call "sensible planning of your class architecture."

You can't grow an architecture from unit tests. Even Uncle Bob says that.

If you're not thinking through the architecture, if what you're doing instead is ignoring architecture and throwing tests together and getting them to pass, you're destroying the thing that will allow the building to stay up because it's the concentration on the structure of the system and solid design decisions that helped the system maintain its structural integrity.

https://hanselminutes.com/171/return-of-uncle-bob#

I think it would be more sensible to approach TDD from a perspective of validating your structural design. How do you know the design is incorrect if you don't test it? And how do you verify that your changes are correct without also changing the original tests?

Software is "soft" precisely because it is subject to change. If you are uncomfortable about the amount of change, continue to gain experience in architectural design, and the number of changes you will need to make to your application architectures will decrease over time.

Related Topic