On the matter of "what should I do about it", there can be many answers.
A more "formal" way of preventing such error conditions while developing is applying design by contract in your code. This means you need to set class invariants, and/or even function/method preconditions and postconditions on your system, while developing.
In short, class invariants ensure that there will be some constraints in your class that will not get violated in normal use (and therefore, the class will not get in an inconsistent state). Preconditions mean that data given as input to a function/method must follow some constraints set and never violate them, and postconditions mean that a function/method output must follow the set constraints again without ever violating them. Contract conditions should never be violated during execution of a bug-free program, therefore design by contract is checked in practice in debug mode, while being disabled in releases, to maximize the developed system performance.
This way, you can avoid NullReferenceException
cases that are results of violation of the constraints set. For example, if you use an object property X
in a class and later try to invoke one of its methods and X
has a null value, then this will lead to NullReferenceException
:
public X { get; set; }
public void InvokeX()
{
X.DoSomething(); // if X value is null, you will get a NullReferenceException
}
But if you set "property X must never have a null value" as method precondition, then you can prevent the scenario described before:
//Using code contracts:
[ContractInvariantMethod]
protected void ObjectInvariant()
{
Contract.Invariant(X != null);
//...
}
For this cause, Code Contracts project exists for .NET applications.
Alternatively, design by contract can be applied using assertions.
UPDATE: It is worth mentioning that the term was coined by Bertrand Meyer in connection with his design of the Eiffel programming language.