What really bothers me the most in some programming languages ββ(e.g. C #, Javascript) is that trying to access the null property throws an error or exception.
For example, in the following code snippet
foo = bar.baz;
if bar is null , C # will NullReferenceException unpleasant NullReferenceException , and my Javascript interpreter will complain about Unable to get value of the property 'baz': object is null or undefined .
I can understand this, theoretically, but in real code I often have somewhat deeper objects, like
foo.bar.baz.qux
and if any of foo , bar or baz is null, my codes are violated. :( Also, if I evaluate the following expressions in the console, the results seem to be inconsistent:
true.toString() //evaluates to "true" false.toString() //evaluates to "false" null.toString() //should evaluate to "null", but interpreter spits in your face instead
I absolutely despise the code to handle this problem, because it is always verbose, smelly code. The following examples are not far-fetched, I grabbed them from one of my projects (the first in Javascript, the second in C #):
if (!(solvedPuzzles && solvedPuzzles[difficulty] && solvedPuzzles[difficulty][index])) { return undefined; } return solvedPuzzles[difficulty][index].star
and
if (context != null && context.Request != null && context.Request.Cookies != null && context.Request.Cookies["SessionID"] != null) { SessionID = context.Request.Cookies["SessionID"].Value; } else { SessionID = null; }
Everything would be much simpler if the whole expression returned null , if any of the properties were null. The above code examples could be much simpler:
return solvedPuzzles[difficulty][index].star; //Will return null if solvedPuzzles, difficulty, index, or star is null. SessionID = context.Request.Cookies["SessionID"].Value; //SessionID will be null if the context, Request, Cookies, //Cookies["SessionID"], or Value is null.
Is there something I am missing? Why don't these languages ββuse this behavior instead ? For some reason, it's hard to implement? Will this cause problems that I donβt notice?