Null Pointer

WhatIsNull?

Languages that use pointers often need a special value to represent an invalid pointer -- a pointer that points to "no object at all." C, C++ and Pascal use a constant/symbol called "NULL" for this.



The SmalltalkLanguage uses a slightly different concept in TheNilObject.

The NULL pointer is a value, not an object. It does not have a "class," nor does it inherit from a class or respond to messages.

A pointer variable, defined as pointing to some particular base class can have the value NULL instead of pointing to an object. In that case, dereferencing the pointer -- by sending a message, for example -- is an "undefined operation" -- typically resulting in program crash.

Thus, using the NullObject pattern, substituting a pointer to a real object with "do nothing behavior," can be more convenient than using the value NULL.


How? NULL is NULL. What would I have to waste a whole object on to signify nothing?

A NullObject is especially convenient in C++ -- if you'd prefer your programs to not crash.

That is, using a NullObject instead of a NULL value can eliminate the need for all your protective 'if' clauses:
 if (pThing) pThing->breathe()


JavaLanguage doesn't have pointers, but it does have NullPointerException, ha ha. This silly misnomer shows how C had infected James Gosling's mind.

It does have references and PointersAndReferencesAreTheSameThing

(See NullPointerException for further, related discussion.)

Is it possible to have an ObjectOrientedLanguageWithoutPointersOrReferences?? I would imagine that it isn't and that some type of Null or Nil or Void value would be difficult to do without.

I think it goes deeper than that, and instead reflects a singularity at the heart of the concept of strong typing. I think the question is whether it is possible to distinguish a "value" from an instance of a Singleton class.

Is "true" a singleton instance of a class called "True" (descended from Boolean) or is it a value of a class with two instances called "Boolean"?

Is there a difference between a type and a class? Can a type be restricted to have only one, two, or N values?

It seems to me that the answers to questions such as these greatly influence the design of our language environments. These become particularly visible in languages that intentionally attempt to separate types from objects, such as Java and CeePlusPlus.

CategoryNull

EditText of this page (last edited August 28, 2007) or FindPage with title or text search