Monday, November 12, 2012

What is null?

What does "null" mean?  You should read null/NULL/nil in the following manner:

"I am not making a statement about the value - it does not exist."

Null is not zero.  Zero is a number.  For languages like Java that support boxing, smalltalk that only has objects, pointers to numeric values, etc, a NULL means THERE IS NO VALUE.  You are not saying it's zero.

Null is not false.  A boolean is a value.  If I'm checking a boolean variable "foo" and it's null, it is not true or false.  If "foo" is false, it has a value.  If "foo" is true, it has a value.  If it's null, then the value has not been set.

Does that mean I have to write 'ugly' code like if(foo is not null and foo)?   That's not ugly code, it's explicit.  if(foo) might work but you're not being clear.  If you intend foo to be false, then set it as false: "foo = false; if(foo) ... ."

There are many subtle bugs that occur because everyone assumes a value had been set for foo, but in fact no value had been set.  It just happens that in your language, null, false and 0 happen to be the same thing.