Non-null objects, the Null Object pattern, and T.init
Ola Fosheim Grøstad" <ola.fosheim.grostad+dlang at gmail.com>
Ola Fosheim Grøstad" <ola.fosheim.grostad+dlang at gmail.com>
Fri Jan 17 06:06:57 PST 2014
On Friday, 17 January 2014 at 01:42:38 UTC, Andrei Alexandrescu
wrote:
> One common idiom to replace null pointer exceptions with milder
> reproducible errors is the null object pattern, i.e. there is
Usually null failures are hard to track when some function
returned a null value as an indication of error when the
programmer expected an exception. In that case early failure is
better.
I guess it cold make sense with "weak" pointers if they are wiped
by the GC.
Like if you delete a User object, then all "weak" pointers are
set to a UnknownUser default object. So that you can call
user.isLoggedIn() and get false, but you should be able to
default to a different Class to get a different set of virtual
calls.
I could also see the use-case for lazy allocation. Basically
having memory-cheap "smart" pointers that are checked when you
trap zero-page access and automatically alloc/init an empty
object before recovering. But the overhead is large.
Not sure if init() is the right way to do it though, because you
might need something more flexible. E.g. maybe you want access to
the node that contained the offending null-pointer.
More information about the Digitalmars-d
mailing list