I've heard it said that the inclusion of null references in programming languages is the "billion dollar mistake". But why? Sure, they can cause NullReferenceExceptions, but so what? Any element of the language can be a source of errors if used improperly.
And what's the alternative? I suppose instead of saying this:
Customer c = Customer.GetByLastName("Goodman"); // returns null if not found
if (c != null)
{
Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!");
}
else { Console.WriteLine("There was no customer named Goodman. How lame!"); }
You could say this:
if (Customer.ExistsWithLastName("Goodman"))
{
Customer c = Customer.GetByLastName("Goodman") // throws error if not found
Console.WriteLine(c.FirstName + " " + c.LastName + " is awesome!");
}
else { Console.WriteLine("There was no customer named Goodman. How lame!"); }
But how is that better? Either way, if you forget to check that the customer exists, you get an exception.
I suppose that a CustomerNotFoundException is a bit easier to debug than a NullReferenceException by virtue of being more descriptive. Is that all there is to it?
Customer
. For all we know it could require DB or network calls for it to function. Thus a single call (fetch) is more efficient than two calls (check and fetch). – gregsdennis Mar 20 '22 at 00:48[myObject methodToCall]
. IfmyObject
is null, then there is no one to receive themethodToCall
message. The net effect is that the method call is silently ignored. It doesn't stop a value from being null; it just handles null better as part of the language. – gregsdennis Mar 20 '22 at 00:54