Disallow null references in safe code?

Idan Arye GenericNPC at gmail.com
Sun Feb 2 07:06:33 PST 2014


On Sunday, 2 February 2014 at 13:55:11 UTC, Adam D. Ruppe wrote:
> On Sunday, 2 February 2014 at 13:15:42 UTC, Dicebot wrote:
>> I agree that there is no much benefit in opt-in null-free 
>> pointers. But if making those opt-out would have been 
>> possible, I'd love it. Breaks every single D program out there 
>> though.
>
> This isn't necessarily so bad. My biggest chunk of code that 
> uses classes is probably my dom.d.... and there's only... I 
> think six functions in there that can return null, and only one 
> property that can be null. (In fact, I think like 1/5 of the 
> lines in there are contracts and invariants relating to null 
> anyway. Once I was getting segfaults because of a corrupted 
> tree and that's ultimately how I tracked it down.)
>
> So if "Element" were changed to be not null by default, the 
> majority of the program should still compile! Then it is a 
> simple case of looking at the compiler errors complaining about 
> assigning null and throw in the Nullable! thingy which 
> shouldn't take that long.
>
>
> Code like
>
> auto a = new A();
> a.foo();
>
> needn't break.
>
>
> Really, I think it would be likely to find more bugs, or at 
> least save time writing dozens of contracts - it would be the 
> "worth it" kind of breakage.

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. Other people - like 
me - treat null as a valid value. 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!

And I'll use the fact that null is D is false and the `if(auto 
foobar=foo.bar)` will only enter the block if `foo.bar` is not 
null, and `foobar` will only be declared in that block, when it's 
guaranteed to not be null.

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`.

So yea, your code won't break. That doesn't mean other code won't 
break.


More information about the Digitalmars-d mailing list