Reopening the debate about non-nullable-by-default: initialization of member fields

Jonathan M Davis via Digitalmars-d digitalmars-d at puremagic.com
Fri May 2 18:21:25 PDT 2014


On Sat, 03 May 2014 00:50:14 +0000
Idan Arye via Digitalmars-d <digitalmars-d at puremagic.com> wrote:

> We are all sick and tired of this debate, but today I've seen a
> question in Stack Exchange's Programmers board that raises a
> point I don't recall being discussed here:
>
> http://programmers.stackexchange.com/questions/237749/how-do-languages-with-maybe-types-instead-of-nulls-handle-edge-conditions
>
> Consider the following code:
>
> class Foo{
> void doSomething(){
> }
> }
>
> class Bar{
> Foo foo;
>
> this(Foo foo){
> doSomething();
> this.foo=foo;
> }
>
> void doSomething(){
> foo.doSomething();
> }
> }
>
> Constructing an instance of `Bar`, of course, segfaults when it
> calls `doSomething` that tries to call `foo`'s `doSomething`. The
> non-nullable-by-default should avoid such problems, but in this
> case it doesn't work since we call `doSomething` in the
> constructor, before we initialized `foo`.

Yeah, I brought this up before, and it's one of the reasons why I'm against
non-nullable by default. It means that class references will need to be
treated the same as structs whose init property is disabled, which can be
_very_ limiting. And I don't know if we currently handle structs with
disabled init properties correctly in all cases, since it's not all that
hard for something subtle to have been missed and allow for such a struct
to be used before it was actually initialized (and the fact that not much
code uses them would make it that much more likely that such a bug would
go unnoticed). Hopefully, all those issues have been sorted out by now
though. If so, then I would think that we already have all of the rules in
place for how non-nullable references would be dealt with with regards to
initialization, but they'd still be very limiting, because most of D expects
that all types have an init property.

- Jonathan M Davis


More information about the Digitalmars-d mailing list