Keyword to avoid not null references

Timon Gehr timon.gehr at gmx.ch
Sat Apr 21 15:51:04 PDT 2012


On 04/21/2012 11:40 PM, Namespace wrote:
> My question is, why D hasn't got an explicit Keyword to check at compile
> time for non null references?

It shouldn't be a special keyword. If the compiler can do the necessary 
analysis to actually enforce that the reference cannot hold a null 
reference, then it should be the default. Most references are not null.

> I understand that such check when they're implicit and refer to all
> objects they slow down the programm,

How would such a check slow down the program? The rest of your post 
seems to indicate that you want a compile time check.

> but why doesn't exist an explicit
> keyword like @ref or a simple '@' before the Object name or value.
> Right now it's very annoying because i get a cryptical error message
> "Access violation" without any further informations and I have to debug.
> Only that way I can find where the Null references would access and
> then, why _and_ where the null references came from. That sucks.
> I hate it and so i write in every method to avoid null references
> "assert(obj !is null);". Now i get an assertion if obj is null and also
> the file and line. 50% less work then before.
> But it's still a runtime error and explicit work which can easily be
> checked by the compiler at compile time.

'Easily' would be an oversimplification. There are distinct issues to be 
solved by the type system, mostly surrounding initialisation.

> Then i know: "oh there are null
> references and there shouldn't be any". So what are the reasons against
> a special keyword to let the compiler check for non references?

There are seldom reasons _against_ a language feature. To make it in, 
there must be reasons to adapt it. And even more importantly, there must 
be a good design that integrates well with the rest of the language.
Having a non-null type system would certainly be desirable, but it would 
be a breaking language change if it was actually designed to be useful.

> I didn't understood it. I heard similar regressions from C# and Java,

In what way would that be a regression?

> so why didn't D made it better and did implement something for that?
>
> Some variants I have already seen: const Foo @obj, const @Foo obj or my
> favourite: const @ref Foo obj.
>
> Greetz

Well, that is the grammar of the feature, but you have not described how 
it should work. (Saying that the compiler should emit an error for null 
references does not cut it.)


More information about the Digitalmars-d-learn mailing list