Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Code Contracts to specify a return value may be null

Is there a way of explicitly specifying that a return value can be null using Code Contracts?

My worry is that methods without a Contract.Ensures(Contract.Result<object>() != null) may be incorrectly 'fixed' in the future to include the post-condition, even though the original intention may have been to allow null results.

like image 753
Lawrence Wagerfield Avatar asked Feb 03 '23 08:02

Lawrence Wagerfield


2 Answers

If there are any other post-conditions then these will indicate that null is a valid return value. For example, if a method should return a positive value but uses null if an error occurs:

Contract.Ensures(Contract.Result<int?>() == null || 0 <= Contract.Result<int?>());

If you're worried about regression, though, the best solution might be to add a unit test for an expected null return value.

like image 118
Matthew Strawbridge Avatar answered Feb 04 '23 23:02

Matthew Strawbridge


If you are using resharper you can get it to produce warnings by marking methods with the CanBeNull attribute as described here: http://blogs.jetbrains.com/dotnet/2010/11/resharper-nullreferenceexception-analysis-and-its-contracts/

Its done using some resharper classes, but convieniently you dont have to reference a library - theres a button in the options to let you get your hands on the annotations. Little thing to be careful of: you need to keep the namespace they are in the same - it appears the actual marking is done by fully qualified name (so putting the classes in your own ns and using them wont produce the warnings you want).

This is very useful for properties that can be null on classes (eg where a user decision is yet to be made/can be removed) but where the assignment is a data object that means it is inappropriate to use the null object pattern. We've got one of those in a project im working on which always trips up new coders who dont realise it can be null.

like image 40
JonnyRaa Avatar answered Feb 04 '23 23:02

JonnyRaa