Code Contracts: Contract.Ensures (5 of n)

Posted on Thursday, July 15, 2010 3:44 PM

This is the first post that will be about post conditions. So far, I’ve tried to shred some light on defining preconditions with the help of the Code Contracts that are now part of the .NET framework since version 4. In the past, preconditions could and would be defined with the help of the IF-THEN-THROW construction. For a broader explanation on that, see my previous post in this series.

Now I’ll move on to post conditions. I have not often included post conditions in my code. Of course you would design your code to never return a null value, of that would be a requirement. But how would you go about checking that? A possible construction would be the following:

    public int Process()
    {
      var processable = from p in this.currentList
                        where p.Processable
                        select p;

      int result = processable.Count();

      // process the bunch....

      if (result != processable.Count())
      {
        throw new Exception("Count does not match number of processed items");
      }

      return result;
    }

The code above has some points to be cautious about. For instance, the value in the variable that is returned might have been changed on a different thread, before it is returned by the method body. How would you verify that? That would not be easy, especially not when your code is not as succinct as it could be and probably has dependencies you were not even aware of. Of course the code above contains a major flaw, since it uses a LINQ query to determine the count of items. But would every developer be aware of this?

Luckily now there is the Contract.Ensures method to the rescue. As I’ve stated before, there is no ‘silver bullet’, and this one is no exception. It does not end all bugs in your code, but it goes a long way. The binary rewriter would make sure the code is checked at the end of the method. But that’s something you could implement yourself. However, the static checker goes the other mile, by checking what you’ve stated must be true. And in the above example, if it were written with the use of Contract.Ensures, the checker would warn you about the fact that the currentList’s entries may have their Processable property changed and therefore it can not verify the correctness of your post condition.

Now back to our main example targeted also in our previous posts. Rewritten with the help of the Contract.Ensures method it will become like this:

    public string RepeatFirstCharacter(string input, int count)
    {
      Contract.Requires<ArgumentNullException>(input != null);
      Contract.Requires<ArgumentException>(input.Length >= 0, "The input should have at least one character.");
      Contract.Requires<ArgumentOutOfRangeException>(count > 0);
      Contract.Ensures(Contract.Result<string>().Length == count);

      return new string(input.ToCharArray(0, 1)[0], count);
    }

This verifies that the length of the returned string value is equal to the int count parameter. An additional check could be the following:

      Contract.Ensures(Contract.ForAll<char>(Contract.Result<string>().ToCharArray(), p => p == input[0]));

This verifies that result only contains the first character of the string input parameter. You may have been wondering what this construction Contract.Result<> is used for. Well, that will be the topic of the next post in this series. And the Contract.ForAll<> will follow in another post as well. Just stay tuned.

That’s it for now.
Meile

Feedback

# Bridal dresses

2/17/2012 3:53 AM by Evening Dress
Ford dresses http://www.inglobaldress.com/ Wedding Dress

# re: Code Contracts: Contract.Ensures (5 of n)

2/27/2012 8:16 AM by hhl
Genuine Costly Air Jordan Shoes Real Affordable Air Jordan Shoes. Actual or fake, Air Jordan shoes are one of the much more expensive footwear obtainable, basketball footwear at

least. But that doesn't stop folks undertaking every thing that they are able to to acquire a pair [url=http://www.jordanshoesauthentic.com/">http://www.jordanshoesauthentic.com/]Authentic Jordan Shoes[/url]. This

is a generalized statement of course, not everybody has to have basketball footwear, but the identical applies to designer handbags and designer clothes. The thing that designer

item fans, including Jordan shoe lovers, should be conscious of is the fact that there are numerous fake or replica designer [url=http://www.jordanshoesauthentic.com/">http://www.jordanshoesauthentic.com/]Authentic

Air Jordan Retro[/url] objects on the market and they have to know what they may be finding.This can be not always so basic to confirm, actually it is not easy to choose which

is genuine [url=http://www.jordanshoesauthentic.com/">http://www.jordanshoesauthentic.com/air-jordan-3-cdp-black-cement-grey-p-170.html]Jordan 3 Black Cement[/url] or fake. In case you have a pair of US$500 or US$99

shoes together and they look the same which one particular is a fake or are they each fake or are they each real[url=http://www.jordanshoesauthentic.com/">http://www.jordanshoesauthentic.com/air-jordan-11-retro-

cool-grey-p-264.html]Air Jordan 11 Retro Cool Greys[/url]? A lot of the footwear will likely be created in the same factories but will be sold at completely distinct charges by

a variety of diverse suppliers.So in the event the footwear sold for US$500 does that make them true or in the event the footwear are sold for US$99 does that make them fake?

This very same factor applies with all the handbags as well as other designer [url=http://www.jordanshoesauthentic.com/">http://www.jordanshoesauthentic.com/air-jordan-retro-11-c-30.html]Cheap Jordan XI[/url]

objects, numerous (within the shoe company virtually all of them) organizations manufacture their merchandise overseas and ship them back to their residence nation and sell them

for huge value markups in comparison with the cost of manufacture [url=http://www.jordanshoesauthentic.com/">http://www.jordanshoesauthentic.com/air-jordan-13-playoffs-p-289.html]Air Jordan Retro 13 Playoffs[/url].

# Great Info.

2/29/2012 8:01 AM by Penegra
hey buddy,this is one of the best posts that I’ve ever seen; you may include some more ideas in the same theme. I’m still waiting for some interesting thoughts from your side in your next post.
http://www.safegenericmeds.com/product/32/generic-viagra.html
http://www.safegenericmeds.com/product/4/kamagra.html

# authentic louis vuitton handbags

3/4/2012 2:56 PM by authentic louis vuitton handbags
http://www.authenticlouisvuitton-handbags.com/

# re: Code Contracts: Contract.Ensures (5 of n)

3/9/2012 7:43 AM by Nike Shox NZ
http://www.cheapairmaxshoes2sale.com
http://www.cheapjordanshoes2sale.com
http://www.cheapshox2sale.com
http://www.nikedunks2sale.com
http://www.cheappumashoes2sale.com
http://www.cheapjordansaaa.com
http://www.cheapairmax2011aaa.com
http://www.cheapshoxnzbuy.com
http://www.cheapdunksbuy.com
http://www.cheappumashoesbuy.com
http://www.nfljerseys2sale.com
http://www.nbajerseystobuy.com
http://www.nfljerseystobuy.com
http://www.nbajerseys2sale.com
http://www.cheapairmax2012buy.com

# re: Code Contracts: Contract.Ensures (5 of n)

3/9/2012 7:43 AM by Cheap Air Max 2011
http://www.gojordanshoes.com
http://www.cheapairmax2011shoes.com
http://www.cheapnikedunks2011.com
http://www.cheapairforceonesshop.com
http://www.cheappumashoesstore.com
http://www.cheapnikeshox2011shoes.com
http://www.salecoachbagsdiscount.com
http://www.onsalecheapnfljerseys.com
http://www.cheapjordans2012shoes.com
http://www.cheapnikeairmax2012.com
http://www.cheapdunks2012.com
http://www.cheapshox2012.com
http://www.cheappuma2012.com
http://www.coogijeansdiscount.com
http://www.cheaplvbagssale.com
http://www.sneakersupplier.com

# cheap jewellry

3/16/2012 2:36 AM by cheap jewellry
your brain healthy with the right diet, and exercising

# Blazers blazers

3/23/2012 6:06 AM by bandage dresse
burgundy party dresses http://www.reviewtrend.net/ Womens clothing.

# longchamp outlet

3/28/2012 8:19 AM by longchamp wallet
For longchamp online details on the core papers and other statistical characteristics of each Front, see the Research Fronts section of the Essential Science Indicators from Thomson Reuters. Some papers have comments sent in by the author(s) of the paper which may include Longchamp luxury bags images and descriptions of their work. http://www.longchampparis1948.com/

# re: Code Contracts: Contract.Ensures (5 of n)

4/6/2012 5:06 AM by cheap Beats By Dre
Thanks for such a helpful tools. I would like to thank you for the efforts you’ve put in sharing this tools.

# Cheap clothes

4/12/2012 12:16 PM by Vintage rings
Wear shop http://www.internaldress.com/ Formal clothing.

# re:oakley sunglasses sale

4/17/2012 9:51 AM by oakley sunglasses sale
Eternal style, concise style and high vogue, little doubt has become oakley whole necessary parts. The oakley sunglasses are new arrival in our look.
<a href="http://www.cheapoakleyonsale.com/">oakley sunglasses sale</a>There are several wonderful promotion activity in our Sunglasses Hut look, simply decide one, opt for your favorite one!

# tradiomir watches

4/18/2012 12:24 AM by replica watch
wenger watches http://www.extendwatches.com/bell_and_ross-watches.html replica watch.

# re: Code Contracts: Contract.Ensures (5 of n)

5/11/2012 5:40 AM by drew-doughty-jersey
http://www.kingsfanshop.com/
http://www.kingsfanshop.com/15-wayne-gretzky-jersey
http://www.kingsfanshop.com/14-ryan-smyth-jersey
http://www.kingsfanshop.com/13-martin-mcsorley-jersey
http://www.kingsfanshop.com/12-dustin-brown-jersey
http://www.kingsfanshop.com/11-drew-doughty-jersey
http://www.kingsfanshop.com/10-anze-kopitar-jersey

# Dresses and wedding

5/14/2012 2:26 PM by Prom Dresses
Black little dresses http://www.alterdress.com/ Day Dress

Post Comment

Title  
Name  
Url
Comment   

ATTENTION: the code you need to copy is CaSe SeNsItIvE and is required to prevent spam.
Enter the code you see:

posts - 24, comments - 125, trackbacks - 0, articles - 0

Copyright © Meile Zetstra