2
votes

I am trying to integrate Code Contracts into some existing code and so far so good for the most part. The problem I am facing though is that I have set up contracts on an interface and one implementation delegates the implementation to a Func<> that is passed into the constructor of the class similar to the following:

[ContractClass(typeof(IFooContract))]
public interface IFoo
{
    object Bar();
}

[ContractClassFor(typeof(IFoo))]
public abstract class IFooContract : IFoo
{
    object IFoo.Bar()
    {
        Contract.Ensures(Contract.Result<object>() != null);
        throw new NotImplementedException();
    }
}

public class DelegatedFoo : IFoo
{
    public DelegatedFoo(Func<object> barImplementation)
    {
        Contract.Requires(barImplementation != null);
        _barImplementation = barImplementation;
    }
    private readonly Func<object> _barImplementation;

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

    public object Bar()
    {
        //"ensures unproven: Contract.Result<object>() != null" here.
        return _barImplementation();
    }
}

The static analyser reports the error "ensures unproven: Contract.Result() != null". Can I define contracts on Func<> (and by extension on Action<>)?

Is this the best solution?

public class DelegatedFoo : IFoo
{
    public DelegatedFoo(Func<object> barImplementation)
    {
        Contract.Requires(barImplementation != null);
        _barImplementation = barImplementation;
    }
    private readonly Func<object> _barImplementation;

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

    public object Bar()
    {
        var result = _barImplementation();
        Contract.Assume(result != null);
        return result;
    }
}
1

1 Answers

0
votes

So, will you always have control over the Func<object> instance passed in? If so, every function referenced by the Func<object> parameter will need to have a Contract.Ensures(Contract.Result<object>() != null) postcondition defined.

The same would be true if you had an Action parameter, instead.

Also, I most definitely would not use Contract.Assume(result != null). Are you sure you'll never return null? What would happen if you did? Try changing that to Contract.Assert(result != null) instead. If you have control over the Func<object> parameter and use postconditions, then you should be able to also specify a postcondition on the public object Bar() method and forego the need for any asserts or assumptions.

Lastly, you may want to consider adding Contract.Ensures(_barImplementation == barImplementation) to your constructor of DelegatedFoo, though, I suppose that the postcondition is covered by the defined invariants. I always like to be explicit—it most certainly can't hurt, especially where the static analyzer is concerned.