Controversial paper: Why Most Unit Testing Is Waste.
I’m not sure I’d go that far, but I will confess that I don’t write unit tests for all, or even most of my code. My view is that there are certain problem domains that are complicated, or where programmers are highly prone to error. Off the top of my head, some examples:
- Anything involving date and time arithmetic.
- Anything involving cryptography.
- Anything involving manual memory allocation.
- Anything involving threads.
- Code to validate human data input.
- APIs someone else is going to use.
- Code which it will be expensive to change.
- Anything involving real money transactions.
That’s definitely not an exhaustive list. But if you’re writing code that does something on that list, then I think you absolutely should have bunch of unit tests. In fact, just this week I wrote a couple of methods for performing some date calculations in Java, and thoroughly unit-tested them with as many pathological examples as I could find on the calendar.
But in big companies, a lot of code is fairly mundane manipulation of data, and much of it is written to tight commercial constraints—meaning the company needs it done quickly, ideally yesterday. I tend to find that in those circumstances, the extra time spent to write code cleanly is a clear win — especially once the throwaway code becomes a permanent mission-critical system. The extra time to unit test everything, on the other hand, doesn’t really stand up to cost/benefit analysis.