Another guy asked a similar question but the answer isn't clear to me.
We have a lot of parameter validation code in our project. They are mostly null parameter checks in public methods only:
if (param == null)
{
throw new ArgumentNullException("param");
}
Those checks aren't part of specification. Their main utility is to get saner stack dumps in case of a programming error. If such a simple check isn't done, you can end up ten levels deep in the stack in a random spot right in the middle of the some other library with a NullReferenceException. This makes the whole backtracing to the root cause process longer. Validation checks are semantically clear and allow you to catch the problems earlier.
Since we're doing that a lot, we have been looking for shorter ways of doing such checks. Such as:
ArgumentHelper.ThrowIfNull(param, "param");
or a similar syntax. We'd like to avoid the overhead basically. The if-throw syntax makes the code unnecessarily long.
When I was experimenting with such syntax I noticed that I was converging to a similar syntax like assertions and code contracts. Code contracts are very attractive because of the possibiltiy of static analysis and catching bugs early in the development cycle.
However as I understand code contracts weren't designed to remedy "input validation" problem or any kind of validation problem whatsoever. Because the exceptions raised by it are not meant to be caught. They are not there for making debugging easier either because default behavior is stripping the code from such checks in the release build. The rewriter just seems like a hack around it and it's not very performant either.
What I understand from all that is "static verification" and "parameter validation" have different goals so they cannot be interchanged. Yet using Code.Contracts for my prologue if-then-throws sounded so natural at the beginning I wonder if I got something wrong.
My question is: Is using code contracts for parameter validation valid? Is there a clear question I can ask to any validation code and come up with an answer like: "yes you can use code contracts to check this" and "no you can't use code contracts to check that"? How do I make the distinction?
I came up with "would that function keep working correctly if I removed the contract statement?". Is that a correct approach?