Sunday, April 15, 2007 10:58 PM
One of the common speedbumps that a lot of teams hit when they move from a traditional development methodology to test driven development (TDD) is to try and figure out where their original tools and practices fit in with this new way of thinking.
One of the most common of these issues is code coverage. A 'pleasant surprise' that you get with TDD is that you'll likely get nearly 100% test coverage for free. Think about it, the core principle of TDD is that you write the test first and then write just enough code that's required for that test to pass. This means, in theory that you should never have any code that wasn't written directly in response to a test. Hence, your unit tests should automatically cover all of your code resulting in 100% test coverage.
Once you realize that you will have extremely high, if not perfect, test coverage as a mere side effect of TDD, it's very tempting to stop performing regular coverage analysis. Don't fall for this siren song, however. There's a very subtle advantage that code coverage can offer you now that it couldn't before you were using TDD. Do you know what it is?
Let's think about it. In TDD, your tests represent the business requirements for your object. Your tests should represent literally everything that the object must be able to do. So if you run coverage analysis and find lines of code that are not being touched by your tests, then you could reason that this code is not required by your object. In other words, you've just found dead or unnecessary code.
Sort of a funny way to think of coverage analysis isn't?
"We don't have code coverage for these lines."
"Should we write more unit tests?"
"Naa, let's just take those lines out."
What's this? Heresy, you say? Blasphemy?
Digital Blasphemy?

Nope, just a different way to think about code coverage. You're tests represent every piece of functionality that your object needs to offer. Your code
under test represents every bit of code required to offer that functionality. What's that mean for your code
not under test? It means that it's not required by your object to do it's one and only job.
Next time you finish a piece of code written using TDD, run coverage analysis on it...just for fun. You may report 100% coverage. You may report less than 100% and have some tests still left to write. Or you may, just maybe, have found some code you didn't even need in the first place.