try/catch idiom in std.datetime

Walter Bright newshound2 at digitalmars.com
Mon Nov 18 14:40:51 PST 2013


I'm glad we're discussing this. There's an important misunderstanding.

On 11/18/2013 2:16 PM, Jonathan M Davis wrote:
> 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.

The point of asserts is that they are supposed to be redundant. (If they were 
not redundant, then they would trip and you'd have a program bug.) Asserts are 
there to detect program bugs, not to validate input data. This is also why the 
optimizer can remove asserts without affecting the meaning of the code.


> 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.

Consider again that std.datetime is chock full of code that requires the 
underlying functions to not throw.

Anytime there is code of the pattern:

    try {
         func();
    } catch (Exception e) {
        assert(0, "func() should not have thrown");
    }

then func() has the wrong API or is being misused.

Again, data validation and bug checking are two very different things and should 
not be combined.

Note that I have screwed this up myself in the std.uni API.


More information about the Digitalmars-d mailing list