null and type safety
Jarrett Billingsley
jarrett.billingsley at gmail.com
Wed Nov 5 05:43:45 PST 2008
On Wed, Nov 5, 2008 at 3:18 AM, Walter Bright
<newshound1 at digitalmars.com> wrote:
> Jarrett Billingsley wrote:
>>
>> The implication of non-nullable types isn't that nullable types
>> disappear; quite the opposite, in fact. Nullable types have obvious
>> use for exactly the reason you explain. The problem arises when
>> nullable types are used in situations where it makes _no sense_ for
>> null to appear. This is where bugs show up. In a system that has
>> both nullable and non-null types, nullable types act as a sort of
>> container, preventing you from accessing anything through them as it
>> cannot be statically proven that the access will be legal at runtime.
>> In order to access something from a nullable type, you have to convert
>> it to a non-null type. Delight uses D's "declare a variable in the
>> condition of an if or while" to great effect here:
>>
>> if(auto f = someFuncThatReturnsNullableFoo()) // f is declared as non-null
>> {
>> // f is known not to be null.
>> }
>> else
>> {
>> // something else happened. Handle it.
>> }
>
> I don't see what you've gained here. The compiler certainly can do flow
> analysis in some cases to know that a pointer isn't null, but that isn't
> generalizable. If a function takes a pointer parameter, no flow analysis
> will tell you if it is null or not.
>
What? Is your response in response to my post at all? I am not
talking about flow analysis on "normal" pointer types. I am talking
about the typing system actually being modified to allow a programmer
to express the idea, with a _type_, and not with static checking, that
a reference/pointer value _may not be null_.
In a type system with non-null types, if a function takes a non-null
parameter and you pass it a nullable pointer, _you get an error at
compile time_.
// foo takes a non-null int*.
void foo(int* x) { writefln("%s", *x); }
// bar returns a nullable int* - an int*?.
int*? bar(int x) { if(x < 10) return new int(x); else return null; }
foo(bar(3)); // compiler error, you can't pass a potentially null type
into a parameter that can't be null, moron
if(auto p = bar(3))
foo(p); // ok
else
throw new Exception("Wah wah wah bar returned null");
With nullable types, flow analysis doesn't have to be done. It is
implicit in the types. It is mangled into function names. foo
_cannot_ take a pointer that may be null. End of story.
More information about the Digitalmars-d
mailing list