Disallow null references in safe code?

Idan Arye GenericNPC at gmail.com
Sun Feb 2 13:18:16 PST 2014


On Sunday, 2 February 2014 at 18:33:05 UTC, Adam D. Ruppe wrote:
> On Sunday, 2 February 2014 at 15:06:34 UTC, Idan Arye wrote:
>> I think it's safe to assume that you - being a supporter of 
>> the non-null movement - write your own code in a way that 
>> tries to avoid the usage of null as much as possible.
>
> You'd be wrong - I was against the not null thing for a long 
> time, including while writing dom.d.
>
>> If I have a class\struct `Foo` with a member field `bar` of 
>> type `Bar`, and an instance of `Foo` named `foo` that happens 
>> to have no `Bar`, I'll not add an extra boolean field just to 
>> indicate that `foo` has no `Bar` - I'll simply set `foo.bar` 
>> to null!
>
> Me too, that's exactly what I did with Element parentNode for 
> instance.
>
>> And I'll use the fact that UFCS works perfectly fine when the 
>> first argument is null to build functions that accept `Bar` as 
>> first argument and do the null checking internally(if it's 
>> needed!) and safely call them on `foo.bar`.
>
> Again. me too.
>
>
> Some of my code would break with not null by default, but the 
> amazing thing is it really isn't the majority of it, and since 
> the compiler error would point just where it is, adding the 
> Nullable! to the type is fairly easy.

OK, I see now. What you say is that even if some code will break, 
it'll be easy to refactor because the compiler will easily 
pinpoint the locations where `Nullable1!` should be added.

Well, I don't think it'll be that straightforward. In order for 
non-nullable-by-default to mean something, most APIs will need to 
use it and not automatically use `Nullable!`. While non-nullabe 
can be implicitly cast to nullable, the reverse is not true, and 
whenever a code fails to compile because it sends nullable-typed 
value to as a non-nullable argument it can't be fixed 
automatically - you'll need to check for nulls, and to actually 
decide what to do when the value is null.

Now, this is doable in your own code, but what if you use a third 
party library? That you are not familiar with it's source? 
Automatically downloaded from a repository that you have 
commit-rights to?


More information about the Digitalmars-d mailing list