Spec#, nullables and more

Adam D. Ruppe destructionator at gmail.com
Fri Nov 5 17:51:02 PDT 2010


> All that does is reinvent the null pointer seg fault.
> The hardware does this for you for free.

The difference is that the hardware tells you when you use it,
whereas the assert tells you when you try to save it.

Let me give you an example from my real world code. I have an xml dom class that I
use in my websites. An element looks like this:

class Element {
   Element[] children;
/* // I didn't write this invariant originally, but always should be there!
   invariant() {
        foreach(child; children)
             assert(child !is null);
   }
*/
   string toString() {
        string ret = "<blah>";
        foreach(child; children)
            ret ~= child.toString();
        return ret ~ "</blah>";
   }
}


Now, let's use it somewhere for a long time. That children list grows and shrinks
as I manipulate the document.

Then, when I'm all done, I say:

writeln(myElement.toString());


And the hardware only now throws its null pointer segfault, all the way at the
very end of the program!

But that's not where the real problem was. Somewhere, I did children ~=
someFunction(); and someFunction returned null for
whatever reason (I don't remember the specifics anymore, but it took almost a full
day to track down!)


I spent most the day tracking this down and the real problem was around line 200
out of the 3500 line program, but the hardware didn't complain until line 3490!



It wasn't until I added the invariant and in/out contracts to all the functions
asserting about null that the problem's true cause became apparent.


More information about the Digitalmars-d mailing list