LA.NET [EN]

Nov 06

In this post we’ll keep looking at how Code Contracts can really help you improve your code. Today, we’ll see how one can use fields and out parameters in contracts. Lets start with fields. Ok, the title is a little misleading…you can use fields in your contract. But what happens when you need to define a contract on an private field from a public method? Well, lets think about this for a minute…your clients must check for values so that they won’t break the contract. If you’re specifying a contract on a private field, then how will a client validate the contract before invoking the method? That’s why there’s a restriction on the visibility of the members you can use in a contract…

In the previous scenario, you could always wrap your field on a property and use the property from within the precondition. However, there may be some cases where calling the property isn’t really desired (for instance, your property might perform some additional tasks which aren’t really necessary when you’re testing the contract). In those cases, and if you have your field is wrapped by a property which is at least as visible as the place where you specifying the contract, then you can use the ContractPublicPropertyNameAttribute and use the field on your contract. Here’s another really simple example:

public class Person
    {
        public Person(String name)
        {
            Name = name;
        }
        [ContractPublicPropertyName("Name")]
        private String _name;
        public String Name {
             get{ /*suppose you have more code here*/return _name;}
             set{ _name = value;}
       }

        public void ChangeName(String name)
        {
            CodeContract.Requires( _name == null);
            Name = name;
        }
    }

If you compile the previous example, you’ll see that you won’t get any errors or warnings and you’ll be able to use a private field on a contract defined on a public method.

Before ending the post, there’s still time to see how you can use out parameters on your contracts. Honestly,I don’t remember the last time I’ve used an out or ref parameter (without being in a interop scenario). Anyway,if you need it, you can use the CodeContract.ValueAtReturn<T> method for using that parameter on a contract. And that’s all for today. More about this framework tomorrow

Leave a Reply

Your email address will not be published. Required fields are marked *


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>