LA.NET [EN]

Nov 08

Before using Code Contracts, you’ll probably already written several lines of validation code for testing requirements on your methods. I’ll keep using the Person class to illustrate some code that you might have before using the Code Contracts library. So, in the past, you might have something like this:

public class Person {
        private String _firstName;
        private String _lastName;
        public String FirstName {
            get { return _firstName; }
        }
        public String LastName {
            get { return _lastName; }
        }
        public void ChangeName(string firstName, string lastName) {
            if( firstName == null )
                    throw new ArgumentNullException("firstName");
            if( lastName== null )
                    throw new ArgumentNullException("lastName");
            _firstName = firstName;
            _lastName = lastName;
        }
}

Now, the first thing you could do is port your code and replace those if-then-throw statements with calls to CodeContracts.Requires method. That might be quite a bit of work! The good news is that if your code is located at the beginning of the method’s body and is similar to the previous example (ie, it’s in the form of if-then-throw), then you can simply add one line of code to the bottom of those tests and you’ll get all the benefits associated with the direct usage of Code Contracts’s methods. Here’s the changes needed for the previous method:

public void ChangeName(string firstName, string lastName) {
    if( firstName == null )
          throw new ArgumentNullException("firstName");
    if( lastName== null )
          throw new ArgumentNullException("lastName");
    CodeContract.EndContractBlock();
    _firstName = firstName;
    _lastName = lastName;
}

Now, if you try writing the following snippet:

var p = new Person();
p.ChangeName(null, null);

You’ll get a warning at compile time. And that’s it for today. More about this on future posts. Keep tuned.

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>