against enforce

Alix Pexton alix.DOT.pexton at gmail.DOT.com
Fri Mar 25 16:53:25 PDT 2011


On 25/03/2011 20:23, spir wrote:
>
> This logic certainly looks sensible, but I cannot understand how it
> should work in practice. Say I'm implementing a little set of operations
> on decimals. Among those, some (division, square root...) will
> necessarily have to check their input.
> According to the rationale you expose, I should use assertions, since
> operand will nearly never be (direct) user input, instead be products of
> the app's logic. Then, what happens when div gets a null denominator on
> a release build? In practice, the issue is not that serious since I will
> certainly delegate to a lower-level func which itself throws. But I
> could also (in theory) implement it in assembly or whatnot.
> My point of view is if a func has preconditions on its args, then
> checkings simply cannot go away.
>
> Such considerations lead me to wonder whether we should not instead use
> exceptions/enforce everywhere for actual func arg checking, and use
> asserts in unittests only. Or use them also for /temporary/ additional
> checkings during development (similar to unittests in fact).
>
> A special case may be about checkings that control logical values or
> ranges which do not prevent the func to run. Say, a.length should
> logically be in 1..9 -- but the func can run fine anyway.
>
> Denis

Since I started programming in D, unittests have been among the first 
things I write, and I am just about getting the hang of using DMD's 
coverage features to make sure that my tests cover every branch of my 
code. Recently I have been trying to write unittests without using any 
additional asserts, making unittests into examples of use, designed to 
hit every corner case while "telling a story". I don't find it quite as 
easy as just writing asserts, but it is a half step toward writing 
decent documentation, (something I often fail at >< ) and it makes the 
code to be tested easier to write.

With the iota case, I want it to use assert, not enforce. I write my 
test so that when it runs it hits the corner cases and if there is a 
problem with the arguments sent to iota then execution stops in the 
library code. In this scenario, I know there is something I need to fix 
in my code (or possibly in Phobos ^^ ). If iota instead threw an 
exception, I would then have to put in a try/catch or a scope() and try 
to recover (to do otherwise would be to duplicate code already in the 
library), but that doesn't fix the problem, it just masks it, so my 
program has gotten worse, not better!

That a compiled lib (including the Phobos lib distributed with DMD) is 
assert-less for performance reasons, is a quality of implementation 
issue, not a fault of enforce, or something it was ever intended to fix.

A...


More information about the Digitalmars-d mailing list