Question

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?

Was it helpful?

Solution

You would use contracts because it allows people using your code to use the static analyser to find errors in their code. Additionally you might want to make sure you implemented the Contract.Ensures methods to so that other programmers know what your function guarantees returning.

You would probably use the alternative requires format for your release code.

public void Toto(string parameter)
{
    Contract.Requires<ArgumentNullException>(parameter != null);
    //...
}

As this version would actually throw the exception if the parameter was null.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top