Spec#, nullables and more

Roman Ivanov isroman.DEL at ETE.km.ru
Fri Nov 5 18:19:09 PDT 2010


On 11/5/2010 8:51 PM, Adam D. Ruppe wrote:
>> 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.

Yep, that's exactly the kind of stuff that makes me wish for non-nulls.
I've been in the same situation many times.

And that's not even the worst case scenario. In the worst case scenario
the inadvertent null gets propagated to a 3d party library that uses it
in some way that doesn't result in program termination, but changes the
logic.


More information about the Digitalmars-d mailing list