try/catch idiom in std.datetime

Jonathan M Davis jmdavisProg at gmx.com
Mon Nov 18 14:16:57 PST 2013


On Monday, November 18, 2013 13:56:39 Walter Bright wrote:
> On 11/18/2013 1:16 PM, Jonathan M Davis wrote:
> > On Monday, November 18, 2013 12:18:31 Walter Bright wrote:
> >> I agree. But I'll add that it would be even better to redesign
> >> FracSec.from
> >> so it never throws at all - have it assert(0) for invalid values being
> >> passed to it.
> >> 
> >> Exceptions should not be thrown for invalid arguments. Data validation
> >> should be handled separately.
> > 
> > I think that that depends. In some cases, it would just mean duplicating
> > work if the API expected the caller to verify the arguments' validity
> > first. A prime example of this would be functions which parse strings. It
> > would be highly inefficient for a function like fromISOExtString to
> > assert instead of enforcing. The caller would have to do the exact work
> > that the function has to do in order to do the check, so it's just
> > wasteful to expect the caller to ensure the validity of the input.
> 
> I think this is exactly a case where you want to have data validation
> separate from operating on that data. Operating on the data should be
> efficient, and it is not if it must also validate.

But that would just duplicate the validation. You validate by parsing the 
string, and you extract the necessary data from it by parsing it. Validating 
the data first would just double the work - on top of the fact that strings are 
most likely to have come from outside the program rather than having been 
generated internally and then parsed internally. This is exactly the sort of 
case where I think that separate validation makes no sense. Separate 
validation only makes sense when the result is _less_ overhead, not more.

Separate validation is of benefit when the caller can avoid the validation in 
most cases, and the function itself doesn't need to do it, so the validition 
only occurs when the caller needs it. If the validation has to be done anyway, 
then there's no point in having separate validation. It just increases 
overhead.

- Jonathan M Davis


More information about the Digitalmars-d mailing list