assert vs. enforce in Phobos code
Jonathan M Davis
jmdavisProg at gmx.com
Tue Feb 25 15:55:50 PST 2014
On Sunday, February 23, 2014 16:10:02 monarch_dodra wrote:
> As a rule of thumb, "enforce" is not necessarily for things
> "user-input" but for things "outside the programmer's control"
> eg: "things that can legitimately fail", Notably, IO, threads,
> databases etc...
>
> If you see any phobos code that validates the range of its inputs
> via an enforce, please knock yourself out and assert it/contract
> it.
assert is used on input to a function when you consider it a programming bug
for it to be given input that does not fulfill that condition. Exceptions are
used when it's considered reasonable for the invalid input to be passed to the
function. Where exactly to draw that line depends on what the function does
and how it's likely to be used. A function that's likely to be used on data
that was input into the program is more likely to use exceptions, whereas on
whose parameters would not have originated from I/O at all are much more
likely to use assertions. Unfortunately, knowing when to use one or the other
is a bit of an art and definitely subjective.
However, in general, I would have thought that std.random would use
assertions, given that its initialization and use does not normally involve
operating on anything that originated from the user even indirectly, and as
such, it's reasonable to require that the programmer give it valid input.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list