5

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?

Crono
  • 10,211
  • 6
  • 43
  • 75
  • possible duplicate of [Throwing an exception vs Contract.Requires?](http://stackoverflow.com/questions/14991647/throwing-an-exception-vs-contract-requirest) – Bob Vale Jan 06 '14 at 19:41

1 Answers1

5

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.

Bob Vale
  • 18,094
  • 1
  • 42
  • 49
  • 2
    That would however requires runtime checking to be enabled for release builds, right? Ain't there drawbacks to this? – Crono Jan 06 '14 at 19:34
  • Yes you need runtime checking for your DLL (but you only need to choose the Release Requires option). There isn't going to be much of a drawback to this compared to the if ... throw approach. And you gain the advantage of being able to document your parameter requires directly into the XML doc – Bob Vale Jan 06 '14 at 19:39
  • Okay, that sounds good! :) Also, it is my understanding that Requires<> method was written with programming exceptions in mind, like ArgumentException, InvalidOperationException or NotSupportedException. In other words, stuff that means something to a software developer. Am I correct? – Crono Jan 06 '14 at 20:04
  • 1
    @crono1981 yes. They are for where you might end up being called by non contract code and wish to pass back meaningful exceptions – Bob Vale Jan 06 '14 at 21:43