Null references redux

bearophile bearophileHUGS at lycos.com
Sat Sep 26 16:32:22 PDT 2009


Jarrett Billingsley:

> Jeremie Pelletier:
> >
> > How would you do this then?
> >
> > void foo(int a) {
> >        Object foo;
> >        if(a == 1) foo = new Object1;
> >        else if(a == 2) foo = Object2;
> >        else foo = Object3;
> >        foo.doSomething();
> > }
> >
> > The compiler would just die on the first line of the method where foo is
> > null.
> 
> Either use Object? (a nullable reference), or factor out the object
> creation - use a separate method or something.

Using a separate function to initialize an nonnull reference is a possible solution, but we can invent nicer solutions too.

You can have a function where inside an object is nullable but returns a nonnull reference, see the enforce() used by Denis Koroskin. (The compiler also has to recognize as a possible "enforce" an if (foo is null) {...}).

Another possible solution is to use something like a Python "with" block that assures something is done when the block is done:

enforce (Object foo) {
    // foo is nonnull, but inside here it's in a limbo
    if(a == 1)
        foo = new Object1;
    else if(a == 2)
        foo = Object2;
    else
        foo = Object3;
} // when the enforce block ends foo must be initialized
foo.doSomething();

Probably there are other possible solutions.

A better solution is to just allow foo to be undefined until it's written over. To simplify analysis it has to be defined when the scope ends.

Bye,
bearophile



More information about the Digitalmars-d mailing list