Existence check for objects

Georg Wrede georg at nospam.org
Wed Jun 13 15:05:00 PDT 2007


Jarrett Billingsley wrote:
> "Georg Wrede" <georg at nospam.org> wrote 
> 
>>Actually, why do we use the foo !is null idiom at all? (Or try to use the 
>>foo != null idiom?)
>>
>>Anyhow, this would seem to be the canonical way to do it in a C family 
>>language in the first place. So maybe we should (of course first mark 
>>o==null as an error, and then) amend the documentation to suggest o itself 
>>as the Politically Correct test for nullness.
> 
> Except there's one tiny inconsistency in the language.
> 
> assert(o);
> 
> This stupidly does not check that o is non-null; instead it runs the 
> object's invariants.  Which, if o really _is_ null, will cause an access 
> violation.  Whee.

Geez!!!

There better be a seriously solid reason for it!

> In this case, you have to write:
> 
> assert(o !is null);
> 
> Other syntaxes to run the invariant, such as "o.invariant()" or "o.assert()" 
> have been proposed, but as usual nothing has come of it. 

An assert test is not the place to gratuituously save a few keystrokes! 
If anywhere, here clarity of expression and consistency are simply 
essential.

If a programmer wants to assert there is an o, the first thing he'd do 
(unless too familiar with the above, er, interesting properties of D) is 
write

   assert(o);

If a programmer wants to assert that the o object is happy and feels 
well, then we should have him write it explicitly. Dammit!

   assert(o.invariant());

or

   assert(o.assert());

or even

   assert(o.thisObjectIsHappy());


Making shortcuts (and saving keystrokes) _in the wrong place_ has 
historically led to grievances and wasted productivity few of us can 
fathom. Don't let this be another example.

---

(Getting my adrenaline up here...) If there *ever* was a place where 
obscurity, short cuts, the unexpected, or inconsistency, are NOT 
welcome, it is debugging related code. For chrissake!

And anybody who finds himself needing to write "assert(o&&o.assert());" 
five times a day, might consider putting this in F1 as an editor macro.

---

After a cigarrette on the balcony, and proofreading, I got to the notion 
that the current behavior is trying to kill two flies in one stroke. 
assert(o) wants to give an access violation if o doesn't exist, and an 
assert failed if the object was unhappy.

Well, I'm sorry but that's not good enough.

As if what I've written above isn't enough, there's one more thing: 
testing whether we have an object at all, and testing whether it is 
happy, belong to entirely different phases of debugging. Rule #1 of 
debugging is, one step at a time.

Still insist on testing both? Write two lines!

Hey, _both_ your boss, and you yourself, should be able to understand 
the code (including the debugging statements) even after the Summer 
vacation.



More information about the Digitalmars-d mailing list