9
votes

I read today about C# 4.0 code contracts. It seems like the common practice for validating a parameter to a method isn't null is as follows:

Contract.Requires(p != null);

However it seems quite unreasonable to me that I'd have to do this for every parameter of every interface method in my code. In the vast majority of cases, the parameters are expected not to be null. I'd expect there would be some sort of mechanism that allows defining some specific parameters are "allowed" to be null (similarly to the "@Nullable" annotation in Java), and that the Contracts framework will automatically ensure the rest aren't null.

Besides saving much time on this "boilerplate checks" (as well as many "Contracts classes", as many times there simply aren't any conditions to be verified except for non-null parameters), it'll also make the contracts code cleaner and more "logic-oriented".

My question is, is there any way to do this, and if not, where isn't there one, or possibly why is my approach here wrong?

1
It would have been useful, but there isn't any shorthand to do this because nobody has changed the language specification to provide one and then implemented it and released it. See Eric Lippert's reply to a similar question here: stackoverflow.com/questions/2806894/… - Matthew Watson
You can use the crn snippet to automatically generate the boilerplate for these not-null statements, which reduces the typing a little. - Matthew Strawbridge

1 Answers

0
votes

I don't agree, null is very helpful when you need to check if something didn't initialized yet, or data was not found, and sometimes you'll want to pass null to a method and its fine, the code contracts are good for common methods that serves lots of classes, and for api definitions. If you write in a layered architecture you just need to protect the interactions between the layers, and you are null safe inside each layer.

your domain got nulls, and its ok.