We have a convention to validate all parameters of constructors and public functions/methods. For mandatory parameters of reference type, we mainly check for non-null and that’s the chief validation in constructors, where we set up mandatory dependencies of the type.
The number one reason why we do this is to catch that error early and not get a null reference exception a few hours down the line without knowing where or when the faulty parameter was introduced. As we start transitioning to more and more TDD, some team members feel the validation is redundant.
Uncle Bob, who is a vocal advocate of TDD, strongly advices against doing parameter validation. His main argument seems to be “I have a suite of unit tests that makes sure everything works”.
But I can for the life of it just not see in what way unit tests can prevent our developers from calling these methods with bad parameters in production code.
Please, unit testers out there, if you could explain this to me in a rational way with concrete examples, I’d be more than happy to seize this parameter validation!
My answer is “it can’t.” Basically it sounds like I disagree with Uncle Bob on this (amongst other things).
It’s all too easy to imagine a situation where you’ve unit tested your library code for non-null arguments, and you’ve unit tested your calling code for a path which happens to provide a null argument to the library without you being aware of it, but which also happens not to cause any problems for that particular path. You can have 100% coverage and actually a pretty good set of tests, and still not notice the problem.
Is everything fine? No, of course it isn’t – because you’re violating the library contract (don’t give me a non-null value) without being aware of it. Can you be comfortable that the only situations in which you’re providing a null argument are ones where it won’t matter? I don’t think so – especially if you weren’t even aware that the argument was null.
In my view, public APIs should validate their arguments regardless of whether the calling code and the API itself is unit tested. Problems in calling code should be exposed, and exposed as early as possible.