X

Invariant code contracts – using class-wide contracts

It is possible to define invariant code contracts for classes. Invariant contracts should always hold true whatever member of class is called. In this posting I will show you how to use invariant code contracts so you understand how they work and how they should be tested.

This is my randomizer class I am using to demonstrate code contracts. I added one method for invariant code contracts. Currently there is one contract that makes sure that random number generator is not null.

public class Randomizer
{
    private IRandomGenerator _generator;

    private Randomizer() { }

    public Randomizer(IRandomGenerator generator)
    {
        _generator = generator;
    }

    public int GetRandomFromRangeContracted(int min, int max)
    {
        Contract.Requires<ArgumentOutOfRangeException>(
            min < max,
            "Min must be less than max"
        );

        Contract.Ensures(
            Contract.Result<int>() >= min &&
            Contract.Result<int>() <= max,
            "Return value is out of range"
        );

        return _generator.Next(min, max);
    }

    [ContractInvariantMethod]
    private void ObjectInvariant()
    {
        Contract.Invariant(_generator != null);
    }
}

Invariant code contracts are define in methods that have ContractInvariantMethod attribute. Some notes:

  • It is good idea to define invariant methods as private.
  • Don’t call invariant methods from your code because code contracts system does not allow it.
  • Invariant methods are defined only as place where you can keep invariant contracts.
  • Invariant methods are called only when call to some class member is made!

The last note means that having invariant method and creating Randomizer object with null as argument does not automatically generate exception. We have to call at least one method from Randomizer class.

Here is the test for generator. You can find more about contracted code testing from my posting Code Contracts: Unit testing contracted code. There is also explained why the exception handling in test is like it is.

[TestMethod]
[ExpectedException(typeof(Exception))]
public void Should_fail_if_generator_is_null()
{
    try
    {
        var randomizer = new Randomizer(null);
        randomizer.GetRandomFromRangeContracted(1, 4);
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message, ex);
    }
}

Try out this code – with unit tests or with test application to see that invariant contracts are checked as soon as you call some member of Randomizer class.

Liked this post? Empower your friends by sharing it!
Categories: .NET C# Testing

View Comments (7)

  • What if your website gunnarpeipman.com could instantly receive a significant surge in traffic? Many businesses overlook thousands of daily visitors simply because they don’t have enough exposure.

    With our AI-powered traffic solution, you can attract 4,000 highly targeted visitors as part of a free trial. If you like what you see, our plans can deliver 350K visitors monthly—helping your site grow. Get more details here: https://ow.ly/W8hy50Vvbm9

  • Every day, websites like gunnarpeipman.com fail to capture valuable traffic opportunities. Don’t let yours be one of them. Our automated traffic system is designed to enhance engagement and bring highly targeted traffic to your site.

    Claim your 4,000 free visitors to test the benefits firsthand. Then, scale up to plans offering up to 350,000 visitors per month. It’s time to realize your website’s true traffic potential. Get started here: https://ow.ly/wlFl50VyXZ8

  • Get more leads for your gunnarpeipman.com website by using AI on Instagram. If you're looking to drive more traffic, generate leads, and grow your brand's reach, you can get more information and start a free trial here: https://ow.ly/1Yh050VyYcH

    This is an AI-powered Instagram growth service that:
    -Increases followers with targeted, high-quality audiences.
    -Boosts engagement through smart AI algorithms.
    -Targets users based on hashtags and accounts they follow.
    -Saves you time by automating tedious Instagram tasks.

    Our service focuses on real, organic growth—no bots, no fake followers. It’s perfect for brands like yours that want to turn Instagram into a lead generation powerhouse. Better yet, our service is provided on a month-by-month subscription basis so you can cancel any time you like. No contracts and a 7 day free trial.

  • Is your website gunnarpeipman.com overlooking its true potential? With our automated traffic system, you might be able to connect with thousands of additional visitors daily—without any extra effort on your part.

    Take advantage of our complimentary offer that delivers 4,000 visitors so you can test the impact. If you love the results, our plans scale up to 350,000 visitors per month. Let’s turn missed opportunities into growth. Get more details here: https://ow.ly/zcWz50VyY3y

  • Wanting to amplify your website growth? Our AI-driven system delivers custom website traffic using keywords and geographic precision from continents to towns.
    Looking to increased revenue, boosted visitors, or greater digital impact?
    We customize it to match your needs. Enjoy a 7-day free trial period with no contract. Dive in here:

    https://ow.ly/u8pX50VyY2P

  • Every day, websites like gunnarpeipman.com miss valuable traffic opportunities. Don’t let yours be one of them. Our smart traffic system is designed to increase exposure and bring potential customers to your site.

    Claim your 4,000 free visitors to experience the benefits firsthand. Then, expand to plans offering up to 350K visitors per month. It’s time to unlock your website’s true traffic potential. Get started here: https://ow.ly/qsrO50VyY7j

  • Working to power your website traffic? Our smart AI tool delivers targeted website traffic using keywords or location zones from continents to neighborhoods.
    Seeking higher earnings, active website traffic, or a wider digital presence?
    We shape it to match your strategy. Enjoy a 7-day free trial period with no contract. Join now:

    https://ow.ly/PZIo50VyY6U

Related Post