Today I’ve been trying to balance several factors in my code following a code review. The first 2 are defensive coding and code noise; some people suggest that wherever an object is used it should first be checked for null, but then what do you do if it is null? sometimes the structure of your code ensures that it is never null. Also having all the null checks just introduces a lot of code noise. One solution would be to have non-nullable types (yes please!), but until that is possible in C# I need some guidelines as to when to check for null.
If an object is guaranteed to be non-null do not bother adding a check for null.
If an object is returned from a method on an interface then the return should always be checked for null.
If an object is returned from a method on a concrete class then the return should be checked for null unless the class has some sort of a guarantee that a null value will never be returned.
These last 2 guidelines show a difference between using an interface and a concrete instance. When you use an interface you can’t guarantee the behaviour of the implementing class, and due to the increased flexibility it would be a bad idea to make these assumptions based on the current implementation (particularly when the implementation is injected or similar). This makes me wonder whether I should spend more time balancing the use of interface dependencies and concrete dependencies.
Any comments welcome; what guidelines do you use for checking for nulls?