Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would I want to use Code Contracts in public methods?

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?

like image 737
Crono Avatar asked Jan 06 '14 19:01

Crono


1 Answers

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.

like image 67
Bob Vale Avatar answered Nov 12 '22 06:11

Bob Vale