In C#, are there any good reasons (other than a better error message) for adding parameter null checks to every function where null is not a valid value? Obviously, the code tha
I agree with Jon, but I would add one thing to that.
My attitude about when to add explicit null checks is based on these premises:
throw
statements are statements. if
is a statement.throw
in if (x == null) throw whatever;
If there is no possible way for that statement to be executed then it cannot be tested and should be replaced with Debug.Assert(x != null);
.
If there is a possible way for that statement to be executed then write the statement, and then write a unit test that exercises it.
It is particularly important that public methods of public types check their arguments in this way; you have no idea what crazy thing your users are going to do. Give them the "hey you bonehead, you're doing it wrong!" exception as soon as possible.
Private methods of private types, by contrast, are much more likely to be in the situation where you control the arguments and can have a strong guarantee that the argument is never null; use an assertion to document that invariant.