Non-null objects, the Null Object pattern, and T.init

Iain Buclaw ibuclaw at gdcproject.org
Fri Jan 17 16:00:16 PST 2014


On 17 Jan 2014 01:45, "Andrei Alexandrescu" <SeeWebsiteForEmail at erdani.org>
wrote:
>
> Walter and I were talking today about the null pointer issue and he had
the following idea.
>
> One common idiom to replace null pointer exceptions with milder
reproducible errors is the null object pattern, i.e. there is one object
that is used in lieu of the null reference to initialize all otherwise
uninitialized references. In D that would translate naturally to:
>
> class Widget
> {
>     private int x;
>     private Widget parent;
>     this(int y) { x = y; }
>     ...
>     // Here's the interesting part
>     static Widget init = new Widget(42);
> }
>
> Currently the last line doesn't compile, but we can make it work if the
respective constructor is callable during compilation. The compiler will
allocate a static buffer for the "new"ed Widget object and will make init
point there.
>
> Whenever a Widget is to be default-initialized, it will point to
Widget.init (i.e. it won't be null). This beautifully extends the language
because currently (with no init definition) Widget.init is null.
>
> So the init Widget will satisfy:
>
> assert(x == 42 && parent is Widget.init);
>
> Further avenues are opened by thinking what happens if e.g. init is
private or @disable-d.
>
> Thoughts?

I would have thought that sort of code would be doable since someone
thought it be a good idea to introduce ClassReferenceExp to the frontend
implementation. :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20140118/310ba0c4/attachment-0001.html>


More information about the Digitalmars-d mailing list