IMHO, since public methods with parameters can be called by any other programmer, it has the responsibility to verify parameter values and throw meaningful ArgumentException
, should any of them be invalid.
That being said, why would I prefer this:
public void Toto(string parameter)
{
Contract.Requires(parameter != null);
//...
}
... over this?
public void Toto(string parameter)
{
if (parameter == null)
throw new ArgumentNullException(nameof(parameter));
//...
}
In the first scenario, runtime contract checking must be enabled for the exception to be thrown. As we know this option is likely to be unchecked for release build, meaning that parameter validation won't occur. For a public method meant to be used by anyone you may or may not know as part of a released product, this seems like a bad idea.
And EVEN if runtime checking is enabled for release builds, the exception that will be thrown back will not be the one a typical .NET developer would expect (ArgumentNullException
in this case).
So what am I missing? Why would I use Code Contracts over "traditional" if-throw pattern?