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

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Thu Jan 16 18:08:06 PST 2014


On 1/16/14 6:02 PM, Peter Alexander wrote:
> On Friday, 17 January 2014 at 01:42:38 UTC, Andrei Alexandrescu wrote:
>> 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.
>
> Hmm, what about derived classes? How do you check for a valid Widget
> given a DerivedWidget.init?
>
> class DerivedWidget : Widget
> {
>      static DerivedWidget init = new DerivedWidget(...);
> }
>
> bool valid(Widget w) { return w !is Widget.init; }
>
> DerivedWidget foo;
> assert(!valid(foo)); // doesn't fire, foo is valid?
>
>
> The nice thing about null is that it is the bottom type, so it is a
> universal sentinel value.

This is a good point.

> Also, what about interfaces? You cannot define an init for an interface.
> Obviously that could just be a known and accepted limitation of this
> proposal, but I'm not a huge fan of solutions that only work in a subset
> of situations. Perhaps there is a solution that I haven't thought of.
>
>
>> assert(x == 42 && parent is Widget.init);
>
> Is that meant to say "x is Widget.init"?

To clarify:

assert(Widget.init.x == 42 && Widget.init.parent is Widget.init);


Andrei



More information about the Digitalmars-d mailing list