Today I (once again) dereferenced an undefined object's property causing a spectacular crashing of our server. Fixing the problem included writing one of my most disliked pieces of boilerplate code, turning
if (foo.bar.baz.id) {...
into
if (foo && foo.bar && foo.bar.baz && foo.bar.baz.id) {...
because baz
happened to be null
in an edge case and this raised an exception.
So my question is: why is dereferencing null/undefined such a problem? Why doesn't foo.bar.baz.something
just safely return undefined
when foo
/bar
/baz
are undefined? I understand the technical why, and am interested in the language design why? Are there languages that have safe dereferencing? Is there a real CS reason for why there aren't, or is it just tradition (inherited form C and it's friends of old)?
I can think of one reason, which is that having more "type checking"-style logic in an action that is as often executed as dereferencing, can slow the language down quite a bit. But then I also think that most of the problem could be solved by having proper exception handling in assignment / if / etc. operators so the dereferencing could just keep on going as is and the "higher level" operators take care of the occasional "oopises".
Another reason I can think of is that it is simply too much of opinionated language design decision to implementing some sort of rule set for how to deal with this issue.
I would greatly appreciate any CS people shedding some light on this issue.