Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I enforce null checking? [duplicate]

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?

like image 948
Juliet Avatar asked Feb 25 '10 21:02

Juliet


People also ask

How do I stop null checks?

One way of avoiding returning null is using the Null Object pattern. Basically you return a special case object that implements the expected interface. Instead of returning null you can implement some kind of default behavior for the object. Returning a null object can be considered as returning a neutral value.

What does a null check mean?

A null indicates that a variable doesn't point to any object and holds no value. You can use a basic 'if' statement to check a null in a piece of code. Null is commonly used to denote or verify the non-existence of something.

Why do we check for null?

It is a good idea to check for null explicitly because: You can catch the error earlier. You can provide a more descriptive error message.

Under what conditions must a foreign key not be null?

A foreign key may not be null when it is part of a composite primary key in the child table.


1 Answers

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.)

like image 163
Jon Skeet Avatar answered Sep 22 '22 08:09

Jon Skeet