Creating code contract postconditions

Just as code contract preconditions control what information is passed to the method under contract, code contract postconditions control what information the method under contract returns to the calling code. You can, therefore, specify that the method will never return a null value or an empty dataset, for example. The actual condition does not matter; this is something that will change on a case-by-case basis. The important thing to remember here is that this code contract allows you to have more control over the data returned by your code.

Getting ready

Assume that the method under contract needs to ensure that the value returned will always be greater than zero. Using a code contract postcondition, we can easily enforce this rule.

How to do it…

  1. Before you start, make sure that you have added the following using statement to the top of your Recipes class:
    using System.Diagnostics.Contracts;
  2. In the Recipes class, add a method called NeverReturnZero() and pass an integer parameter to this method:
    public static class Recipes
    {
        public static int NeverReturnZero(int iNonZeroValue)
        {
               
        }
    }
  3. Inside the method, add your postcondition contract. As one could expect, the method in the contract class is called Ensures. This is quite descriptive of its function. The code contract ensures that a specific method result is never returned. You can see this in the signature of the Contract.Ensures method. The postcondition, therefore, ensures that the result of this method will never be zero:
    public static int NeverReturnZero(int iNonZeroValue)
    {
        Contract.Ensures(Contract.Result<int>() > 0, "The value returned was not greater than zero");
                
        return iNonZeroValue - 1;
    }
  4. Go back to the console application, and add the following using statements:
    using static System.Console;
    using static Chapter8.Recipes;
  5. Since you 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. Pass the NeverReturnZero() method a value of 1:
    try
    {
        NeverReturnZero(1);
    }
    catch (Exception ex)
    {
        WriteLine(ex.Message);
        ReadLine();
    }
  6. Finally, run your console application and review the output in the console window:
    How to do it…

How it works…

When the value of 1 was passed to the method under contract, it resulted in a return value of zero being returned. We forced this by subtracting 1 from the parameter passed to the method. As the method ensures non-zero values, an exception was thrown with the message we defined.

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

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