On 2013-11-18 23:45, Andrei Alexandrescu wrote:

The question is what's "program" and what's "input". Consider:

int a = fun();
std.gun(a);

There are two possible takes on this:

1. The standard library is considered part of the user's program, and
the whole thing is a unit. In that case, passing the wrong int to
std.gun is an PROGRAM error and 100% blame goes to the programmer who
wrote the caller code. In that case, assert/assert(0)/contracts are the
appropriate constructs to be used inside std.gun.

This is the approach taken by the C standard library, which is free to
do whatever it wants (including crashing the program) upon calls such as
strlen(NULL) etc.

In D, we can start by saying that all private and package functions should use asserts.

2. The standard library is a separate entity from the PROGRAM, and as
far as it cares, any data from the user is INPUT. So the standard
library with SCRUB the input, in which case enforce() and throwing
exceptions are appropriate.

This is the approach taken by the Windows API, Java, C#, and to a good
extent the newer parts of C++'s standard library.

To claim that one approach is exactly right and the other is exactly
wrong would miss important insights.

I agree, it's not easy to just pick one. Say you have a library that queries a database. Is it the user's responsibility to validate any input that it doesn't contain SQL injections. Or should the library do that?

I would say that it would be quite cumbersome and verbose to for the user to constantly validate the input. If the library didn't validate the user would most likely create a wrapper function that does this. Most users would want to have a function like this and implement it. When we come to this, one can ask, isn't this the job of the library? If every user needs it, shouldn't it be put in the library?

--
/Jacob Carlborg

Reply via email to