"is null" vs "== null"

Søren J. Løvborg web at kwi.dk
Sat Mar 25 08:01:28 PST 2006


I find it problematic that comparing null-values with the == operator 
crashes D programs.

I'm aware of the reason (namely, that a == b is translated to 
a.opEquals(b) ), but nevertheless, I'm afraid this may be a big newbie-trap, 
and that it will cause people to avoid D.

At the very least, the compiler should trap obviously wrong expressions like 
"obj == null" and "obj != null", which simply doesn't make sense with the 
current semantics of the == operator.

But also for experienced D programmers, I believe the current == semantics 
to be dangerous, in that a potential segmentation fault lies hidden behind 
an innocuous == operator.

Since a null value often represents abnormal conditions, such a potential 
crash could easily go unnoticed, even with plenty of testing. How do you 
explain to a client that their server crashed with a segmentation fault 
because you accidentally used "==" instead of "is" on a value (that 
unfortunately never became null during testing)?

Such problems may be due to bad software engineering, but I believe that 
they are very real.

I'd much rather see the == operator extended to deal with null-values.
    if (a == b) { ... }
should be translated to
    if (a == null ? (b == null) : a.opEquals(b)) { ... }

Pro: No hidden threat of segfaults/GPFs in a simple equality test. Plus, it 
makes sense that null equals null (and null only), even when comparing 
values ("==") rather than references ("is").

Con: This would add some overhead, though I believe that it would be 
negligible to the existing overhead of the opEquals call. For performance 
intensive operations, one should use the "is" operator, or call opEquals 
explicitly.

Thoughts?

Søren J. Løvborg
web at kwi.dk 





More information about the Digitalmars-d mailing list