A better assert() [was: Re: std.unittests [updated] for review]

Adam D. Ruppe destructionator at gmail.com
Fri Feb 4 16:07:30 PST 2011


bearophile wrote:
> What is [normal assert exceptions] useful for?

Getting a more helpful error message and stack trace.

> If I want a HALT (to tell the compiler a point can't be reached,
> etc) I want it in every kind of compilation of the program.

assert(0) does just that. Either way, the program stops.

> The replacement for assert(0) is meant to be more clear in its
> purpose compared to assert(0). It may be named [...] assertZero(), etc.

LOL!

But, assert(0) does exactly what it says - assert this situation
is invariably invalid.

> Something like class_instance.invariant() is better because:
> - It's explicit and readable.

So is assert(obj);

If the null check bug wasn't there, I doubt anyone would complain
about the invariant. Hell, people who didn't read the manual
would probably have no idea it even did it!

The invariant is, well, invariant. A method isn't allowed to
return without checking it, meaning the only reference where it
might fail is assert(this). (Assuming the null bug was fixed.)

assert(this) inside a method doesn't make too much sense for
null checks anyway. this is rarely null.

> - It removes a special case, and special cases kill languages.

This isn't really special. You're asserting the object is
valid, which includes the invariant. If you want to only assert
it is not null, you should write assert(obj !is null);

Also, if you change to obj.invariant(), it will probably never
be used. assert() is your one-stop shop for sanity tests.

> Struct instances too allow an invariant, but they are not
> callable with assert(), see below.

IMO that's the bug. It'd make a lot more sense to fix it so
assert(struct) checks the invariant than to break assert(class)
so it doesn't.


More information about the Digitalmars-d mailing list