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?
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.
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.
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.
A foreign key may not be null when it is part of a composite primary key in the child table.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With