Creating code contract preconditions

Preconditions allow you to control exactly what the parameters need to look like before they are used in your method. This means that you can assume a lot of things about the data being sent to your method by the calling code. You can, for example, specify that a parameter should never be null or that a value must always be within a specific value range. Dates can be checked, and objects can be verified and vetted.

You have complete control over the data coming in to your method. It gives you the peace of mind to use that data once it has passed your contract without having to do additional checks.

Getting ready

Be sure that you have installed code contracts and that you have configured the settings correctly in the project properties, as described in the previous recipe.

How to do it…

  1. In your Recipes class, create a new method called ValueGreaterThanZero() and have it take an integer as a parameter:
    public static class Recipes
    {
        public static void ValueGreaterThanZero(int iNonZeroValue)
        {
               
        }
    }
  2. In the ValueGreaterThanZero() method, type the start of the Contract declaration, and you will notice that the code is underlined with a red squiggly line. Hold down Crtl + . (period) to bring up the suggestions for potential fixes. Click on the suggestion to add the using statement for the code contracts to your class:
    How to do it…
  3. When you have done that, continue entering the precondition. Define that the parameter value must be greater than zero:
    public static void ValueGreaterThanZero(int iNonZeroValue)
    {
        Contract.Requires(iNonZeroValue >= 1, "Parameter iNonZeroValue not greater than zero");
    }
  4. If you go back to the console application, add the following using statements:
    using static System.Console;
    using static Chapter8.Recipes;
  5. Since we have created a static class and brought it into scope with the using statement, you can just call the method name in the Recipes class directly. To see how code contracts work, pass a zero parameter to the method:
    try
    {
        ValueGreaterThanZero(0);
    }
    catch (Exception ex)
    {
        WriteLine(ex.Message);
        ReadLine();
    }
  6. Finally, run your console application and see the exception generated:
    How to do it…

How it works…

The code contract has inspected the precondition and determined that the parameter value passed to the method under contract failed the precondition check. An exception is thrown and output to the console window.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.206.69