NullIsObject
If a variable is set to null
,
this means it points to a null
object on the heap.
null is an object
null is a reference pointing to no object
CorrectionHere is what's right.
null
is a value that does not point to anything.
All other reference values point to some heap object,
but null
means that it does not point anywhere.
OriginWhere could this misconception come from?
Students may have prior exposure to languages like Smalltalk or Self,
where every value is an object.
In a language like Self,
nil
indeed is an object.
(Self’s nil
takes the same role as Java’s null
.)
ValueHow can you build on this misconception?
This misconception provides a good opportunity
to introduce the dangers of null
,
as explained by its inventor:
Turing Award winner Tony Hoare introduced the idea of a Null reference
in ALGOL W back in 1965 “simply because it was so easy to implement”.
In his QCon London 2009 presentation
he talks about that decision and considers it his “billion-dollar mistake”.
The “Null Object” or “Sentinel Object” idioms,
or the Nothing
case of a Maybe
or Optional
monad,
all represent the absence of a value with a special object,
and represent a way to fix Hoare’s billion-dollar mistake.
Thus, it’s really not that crazy an idea to consider null
to be a special,
singleton, object.