Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What would we do without NULL?

Tags:

I once read that having nullable types is an absolute evil. I believe it was in an article written by the very person who created them(in Ada?) I believe this is the article

Anyway, so what if by default a language like C# used non-nullable types? How would you replace some of the common idioms in C# or Ruby or any other common language where null is an acceptable value?

like image 503
Earlz Avatar asked Aug 03 '10 03:08

Earlz


1 Answers

Instead of outright declaring that nullable types are evil, I would posit: most languages graft nullability onto entire kinds of types, when the two concepts should really be orthogonal.

For example, all non-primitive Java types (and all C# reference types) are nullable. Why? We can go back & forth, but ultimately I'll bet the answer comes down to "it was easy". There's nothing intrinsic to the Java language that demands widespread nullability. C++ references offered a fine example of how to exorcise nulls at the compiler level. Of course, C++ has a lot more ugly syntax that Java was explicitly trying to curtail, so some good features ended up on the cutting floor alongside the bad.

Nullable value types in C# 2.0 offered a step in the right direction -- decoupling nullability from unrelated type semantics, or worse, CLR implementation details -- but it's still missing a way to do the opposite with reference types. (Code contracts are great & all, but they're not embedded in the type system the way we're discussing here.)

Plenty of functional or otherwise obscure languages got these concepts "straight" from the beginning...but if they were in widespread use, we wouldn't be having this discussion...

To answer your question: banning nulls from a modern language, wholesale, would be just as foolish as the so-called "billion dollar mistake." There are valid programming constructs where nulls are nice to have: optional parameters, any sort of default/fallback calculation where the coalesce operator leads to concise code, interaction with relational databases, etc. Forcing yourself to use sentinel values, NaN, etc would be a "cure" far worse than the disease.

That said, I'll tentatively agree with the sentiment expressed in the quote, so long as I may elaborate to fit my own experience:

  1. the # of situations where nulls are desirable is smaller than most people think
  2. once you introduce nulls into a library or codepath, it's much harder to get rid of them than it was to add them. (so don't let junior programmers do it on a whim!)
  3. nullable bugs scale with variable lifetime
  4. correlary to #3: crash early
like image 106
Richard Berg Avatar answered Oct 23 '22 22:10

Richard Berg