Why dont dlang check NullPointer?

w0rp via Digitalmars-d digitalmars-d at puremagic.com
Tue Mar 31 08:30:43 PDT 2015


On Tuesday, 31 March 2015 at 08:17:29 UTC, zhmt wrote:
> On Tuesday, 31 March 2015 at 07:48:08 UTC, w0rp wrote:
>
>> I argue that instead of catching NullPointerExceptions, you 
>> should make them never happen. This is where Option types come 
>> in. Rather than using T*, use an Option!T and force yourself 
>> to always check for null gracefully. Also use Some!T (a.k.a 
>> NotNull) and get classes and pointers which are verified via 
>> contracts that they are not null.
>>
>> I have already implemented such a thing here.
>>
>> https://w0rp.com/project/dstruct/dstruct/option/
>>
>> If you don't like it, you can always implement a similar thing 
>> yourself.
>>
>> Now at this point you might wish for this to gain some 
>> benefits from being a language feature. I think I will agree, 
>> but who knows if that will ever happen.
>
> Maybe this a good direction.
>
> A pointer or reference is replaced by a struct (a pointer 
> holder?), and the struct will check if the pointer is null.
>
> It is a good idea, I could check the pointer myself now, and 
> stopping worring about server crashing, that's enough.
>
> Excellent job, Thank you!

It's a commmon pattern now. I think I personally copied the way 
Scala does it. I used contracts for the checks, and my hope is 
that with the contracts off and the right optimisations, you can 
get roughly the same code generated as if you didn't use the 
option types at all.

I think my inclusion of opApply on the Option type was a mistake. 
I will probably remove that in future. I have a function for 
creating a range from them anyway. Feel free to try my types if 
you like. I haven't tested them enough to figure out how 
effective they are, or there are any bugs I missed.


More information about the Digitalmars-d mailing list