The Right Approach to Exceptions

Jonathan M Davis jmdavisProg at gmx.com
Thu Feb 23 12:07:40 PST 2012


On Thursday, February 23, 2012 07:47:55 H. S. Teoh wrote:
> On Thu, Feb 23, 2012 at 02:57:43AM -0800, Jonathan M Davis wrote:
> [...]
> 
> > DbC tends to work better with internal stuff where you control both
> > the caller and the callee, whereas defensive programming works better
> > with public APIs.  But regardless, which is best to use depends on the
> > situtation and what you're goals are.
> 
> [...]
> 
> The way I understand it, DbC is used for ensuring *program* correctness
> (ensure that program logic does not get itself into a bad state);
> defensive programming is for sanitizing *user input* (ensure that no
> matter what the user does, the program doesn't get into a bad state).
> 
> That's why DbC is compiled out in release mode -- the assumption is that
> you have thoroughly tested your program logic and verified there are no
> logic problems. Input sanitizing is never compiled out, because you
> never know what users will do, so you always have to check.
> 
> The two do somewhat overlap, of course. For example, failing to sanitize
> user input may eventually lead to passing invalid arguments to an
> internal function.

Exactly. But where things tend to blur is the concept of "user input." For 
instance, if you're using a 3rd party library, should it be asserting on the 
arguments that you pass it? Unless you compile it in non-release mode, it 
obviously won't, which could be an argument for using exceptions, but 
regardless of that, from the library's perspective, you're a user. If it used 
DbC, it would be putting assertions it in its own code to test _your_ code. 
And since you're a user, it arguably should use exceptions to make sure that 
the arguments that it gets are correct. So, it all tends to get blurry, and 
the best decision varies from situation to situation. It's also part of what 
makes the concept of assertion vs exception harder for some folks (and as nice 
as enforce may be it, it blurs the line even further for many people IMHO, 
since it then makes exceptions the same as assertions syntactically).

Arguably, the best thing would be if there was a way for the caller to 
indicate whether it wanted the callee to have DbC enable and possibly even 
indicate whether it wanted the callee to use DbC or defensive programming. But 
there's no way to do that in D, and I'm not sure that it could even be done 
with the C linking model - at least, there's no way to it without templatizing 
everything and giving an argument to the template indicating what you want, 
which obviously isn't a good solution (and won't work at all in the case of 
virtual functions, since they can't be templatized).

- Jonathan M Davis


More information about the Digitalmars-d mailing list