Postmortem: Template unittests are bad & you shouldn't catch Error

H. S. Teoh hsteoh at quickfur.ath.cx
Thu Oct 22 16:30:57 UTC 2020


On Thu, Oct 22, 2020 at 04:05:51PM +0000, Mathias LANG via Digitalmars-d wrote:
> On Thursday, 22 October 2020 at 14:36:11 UTC, Steven Schveighoffer wrote:
> > On 10/22/20 12:04 AM, Mathias LANG wrote:
[...]
> > > Second, as the title of the post says, *do not catch Error*.
[...]
> > I disagree with this. How would you test that the assert error is
> > thrown? It seems that your specific case is being hampered by this,
> > but can't you just look at the parameters to see whether you should
> > handle it or not? Like check the file/line and do the normal thing
> > if it's from phobos?
> 
> You do not test for assert error. Assert errors are logic errors, and
> if they get triggered, all bets are off. Of course, one might find
> this impractical, because `get` cannot be tested this way. Perhaps
> that's a sign that `Nullable` should use exceptions, and not `assert`,
> for this.
[...]

+1.  Catching Errors is an anti-pattern and a code smell.  The usual
argument is, I want to test that my asserts are working.  The problem
with that is that it quickly falls into the paradox of who watches the
watchers.  The next thing you know, I'm asking for a way to test that my
code that catches asserts are actually catching asserts.  Next year I'll
be asking for code to test my code that tests code that catches asserts.
It never ends.

The point is, if your asserts are so complex you have to write unittests
for them, then there's something fundamentally wrong with them, and they
should be rewritten. Like with exceptions, as Mathias says.

It's a different story altogether if druntime uses catching of Errors as
a low-level mechanism to implement certain language semantics.  I know
contracts in a class hierarchy are implemented that way for certain
reasons, for example.  But that's stuff under the hood, that should not
be done in user code, ever.


T

-- 
Obviously, some things aren't very obvious.


More information about the Digitalmars-d mailing list