Code Contracts and compatibility with existing code

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.

Advertisements

~ by Luis Abreu on November 8, 2008.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: