-1

Is that true that Code Contracts static analysis cannot check the explicit return new ... in a single branch methods (methods that don't have any conditionals and have only one return) like:

static public Tuple<int> Foo()
{
    return new Tuple<int>(42);
}

still warns me with

warning : CodeContracts: Possibly calling a method on a null reference. Do you expect that SomeClassName.Foo() returns non-null?

I indeed can help a static checker with

Contract.Ensures(Contract.Result<Tuple<int>>() != null);

explicitly but it looks like a huge overhead.

So my question is: am I missing something or that's my obligation to Ensure even such a trivial cases?

zerkms
  • 249,484
  • 69
  • 436
  • 539

1 Answers1

1

When calling out to other methods, code contracts relies on what has been explicitly stated. As you are suggesting, it could probably work this out in some cases but in general, do you really want it to? For a trivial example like this, it does make sense, but in general, just because a method currently doesn't return null that doesn't mean that the author is explicitly guaranteeing that.

This is where the contracts come in, rather than just describing what the code does, it is describing what you are guaranteeing the code will do which is a slightly different thing. So to answer your question, yes, even though it is a bit of an overhead for trivial cases, it is you have to Ensure these trivial cases.

TomDoesCode
  • 3,580
  • 2
  • 18
  • 34
  • "but in general, just because a method currently doesn't return null that doesn't mean that the author is explicitly guaranteeing that." --- well, in general I just don't want false negatives, that bring noise to the IDE :-) – zerkms Apr 11 '16 at 21:43
  • Btw, alternatively it can also be constrained on the caller side. – zerkms Apr 11 '16 at 21:44