When should I guard against null arguments? Ideally, I would guard against null everywhere, but that gets very bloated and tedious. I also note that people aren’t putting guards in things like AsyncCallbacks.
To keep from annoying other people with lots of unidiomatic code, is there any accepted standard as to where I should guard against null?
Thanks.
One approach which I have used a lot is the null object pattern.
For example, if a have a factory class which returns different implementations of an interface based on an argument, and the provided argument is not mapped to any of the implementations, I would return a NullObject,
e.g.
When I want get an
IFoofromCreateFoo, I don’t have to check whether the returned object is null.Obviously, this is just one of the many approaches. There is no “one size fits all” since null can mean different things.
Another way to guard against null arguments is to use CodeContract preconditions.
e.g.
Using Code Contracts allows you to run static code analysis against your code and catch bugs such as
Foo(null). (more here)One more why to do it would be to use a very simple generic extension method:
Then you can check your arguments like this: