null and type safety
Denis Koroskin
2korden at gmail.com
Tue Nov 4 06:09:31 PST 2008
On Tue, 04 Nov 2008 00:10:29 +0300, Brendan Miller <catphive at catphive.net>
wrote:
> So I'm curious about D as a programming language, especially as it
> compares to C++.
>
> One problem that C++ made a partial effort to solve was that normal
> pointers in C++, and references in languages like Java and C#
> essentially aren't type safe.
>
> Consider that null can always be assigned to a pointer or reference to
> type T in those languages, and null is clearly *not* of type T, thus
> operations on a variable denoted of type T, are doomed to fail.
>
> T *myObject = null;
> myObject->myMethod(); // fails, despite the fact that myObject is of
> type T
> // and myMethod is defined for
> type T.
>
> Null is a holdover from C and has no place in a typesafe language. The
> designers of C++ knew this, and so introduced the c++ reference type:
>
> T &myObjectRef = ...;
>
> which cannot be null.
>
> T &myObjectRef = null; // fails at compile type
> T &myObjectRef = *ptr; // if ptr is null, operation is "undefined".
>
Unfortunately, you can have null references in D:
Object o = null;
> The designers of Java and C#... copied C's typesystem largely for
> marketing purposes and never really thought through these issues
> (although I read an interview where Anders Hejlsberg admitted this was a
> mistake with C# that occured to him too late to fix).
>
Yes, I agree this is a mistake and D could learn a lesson from C#/Java.
> This is obviously a problem. Everyone knows that null pointer exceptions
> in Java/C#, or segmentation faults in C and C++ are one of the biggest
> sources of runtime errors. Furthermore, there's no reason whatsoever
> that these problems can't be caught by the compiler in a strongly typed
> language like C++ that has the idea of a non-nullable pointer. The whole
> point of type annoations is to catch these errors before runtime after
> all. Otherwise it's just a lot of useless typing. C++ partially solves
> the problem partially with references, and truly static safe typed
> language like ML solve this problem by making variables typesafe by
> default, and using an Optional type to wrap nullable types.
>
> So my question, is, as the successor to C++, how does D solve this
> problem? I'm looking through the D docs, that are a little sparse, but
> I'm not seeing any references to pointers that can't be nulled.
>
> Brendan
Nullable types have been proposed several times by many people, but I
don't recall any respond from Walter or Andrei :(
More information about the Digitalmars-d
mailing list