How do I enforce null checking?

2019-01-18 04:11发布

I'm working on a large project where, even with 10s of 1000s of automated tests and 100% code coverage, we're getting a ridiculous number of errors. About 95% of errors we get are NullReferenceExceptions.

Is there any way to enforce null-checking at compile time?

Barring that, is there any way to automagically enforce null-checking in unit tests without having to write the tests for null cases myself?

12条回答
劫难
2楼-- · 2019-01-18 04:44

This isn't a technical solution, but a social one. Simply make it unacceptable in your environment to access a reference type without checking for null when the reference type has been modified in any way by outside code (another method call, etc). Unit Testing doesn't replace good old-fashioned code review.

查看更多
疯言疯语
3楼-- · 2019-01-18 04:49

Defensive programming can only get you so far... maybe its just better to catch the exception and deal with it like any other.

查看更多
We Are One
4楼-- · 2019-01-18 04:49

neither of those is possible with C# 3. you would have to use something like Spec#... i think C#4 may have some of that built into it, but i'm not sure about that.

spec#: http://research.microsoft.com/en-us/projects/specsharp

查看更多
Root(大扎)
5楼-- · 2019-01-18 04:56

You should look into Code Contracts. The static checker is only available for the higher-end VS editions, but that's basically what you're after.

There are plenty of resources online, and <plug> you can also read a prerelease version of the chapter on Code Contracts from the 2nd edition of C# in Depth - download chapter 15 for free. </plug> (The chapter is slightly out of date with respect to the latest and greatest build of Code Contracts, but nothing huge.)

查看更多
倾城 Initia
6楼-- · 2019-01-18 04:56

Is there any way to enforce null-checking at compile time?

Nope. The compiler cannot determine if the run-time reference variable is pointed to null.

And ruling out null producing statements (sets and returns) isn't enough either. Consider:

public class Customer
{
  public List<Order> Orders {get;set;}
}
  //now to use it
Customer c = new Customer;
Order o = c.Orders.First(); //oops, null ref exception;
查看更多
The star\"
7楼-- · 2019-01-18 04:57

1) I think, the Resharper can suggest you to check some critical places in your code. For example, it suggests to add the [null reference check code] and adds it if you allow.

Try it. It will increase your experience if you need, of course.

2) Use "Fail Fast" pattern (or assert, assertions) in your code at the early stage of development application

查看更多
登录 后发表回答