Saturday, December 5, 2009

Practical TDD

Recently I was asked (twice) whether I preferred to write test first (as it's implied by TDD). Some time ago I published a post at my old blog
http://dima-ch.blogspot.com/2007/04/test-or-not-to-test-first.html

I still believe that it depends on a situation.
When it's a new system that needs to have as good and testable design as possible - this is definitely a case when tests should be written first. As soon as most people prefer not to make additional work (like creating 10 classes instead of one) they will create (it's not guarantied but very probable) concede methods and methods with meaningful names (which is good for code readability). Thus while following test-first practice the good design will be created 'for free' (nothing is free but a cost should be affordable)

Another case is when you have existing system which has no unit tests at all or only few up-to-date. In most cases design decisions for a system are known and changing then is rather difficult and not always needed. In such cases I may create tests for new functionalities after adding some methods. Unit tests in this case are used as short test programs to debug and validate some methods. Sometimes I don't even know what exact result a method should return. Imagine a case when you have a formula that should process a million of entries. You may know the formula but not results until you have the first run. So I may debug a function, run it with some parameters without assertions. After stooping at a breakpoint I note an output value, then modify the test and add assertion for this value. If I find more cases I just add more unit tests to cover all typical ones.

Anyway, I believe that the main measure for unit tests is the code coverage. If you have a code coverage constantly high (90% or even more) then no matter in what order you write tests if you have everything working and tested.

No comments: