Checking function parameters in Phobos

Jacob Carlborg doob at me.com
Wed Nov 20 03:57:23 PST 2013


On 2013-11-20 11:38, Jonathan M Davis wrote:

> Unfortunately, I don't think that it scales at all to take the approach that
> Walter has suggested of having the API normally assert on input and provide
> helper functions which the caller can use to validate input when they deem
> appropriate. That has the advantage of giving the caller control over what is
> and isn't checked and avoiding unnecessary checks, but it also makes it much
> easier to misuse the API, and I would expect the average programmer to skip
> the checks in most cases. It very quickly becomes like using error codes
> instead of exceptions, except that in this case, instead of an error code
> being ignored, the data's validity wouldn't have even been checked in the first
> place, resulting in the function being called doing who-knows-what. And the
> resulting bugs could be very obvious, or they could be insidiously hard to
> detect.

I think Walter suggestion requires the use of asserts:

bool isValid (Data data);

void process (Data data)
{
     assert(isValid(data));
     // process
}

The asserts should be on by default and remove in release builds. This 
would require DMD shipping two versions of Phobos, one with asserts 
enabled and one where they're disabled. Then only when the -release flag 
is used the the version of Phobos with disabled asserts will be used.

> Still, the most important point that I'd like to make is that I think we
> should lean towards validating input with enforce by default and then provide
> alternative means to avoid that validation rather than using assertions and
> DbC by default, because leaving the validation up to the caller in release and
> asserting in debug is going to lead to _far_ more bugs in code using Phobos,
> particularly when the result isn't immediately and obviously wrong when bad
> input is given. And the fact that by default, the assertions in Phobos won't
> be hit in calling code unless the Phobos function is templatized (because
> Phobos will have been compiled in release) makes using assertions that much
> worse.

DMD need to ship with two versions of Phobos, one with assertions on and 
one with them disabled.

-- 
/Jacob Carlborg


More information about the Digitalmars-d mailing list