On Friday, March 18, 2011 09:08:38 Kagamin wrote: > Steven Schveighoffer Wrote: > > This is a good example of why it's difficult to decide what "user input" > > is. One could consider that the 'user' in this case is the developer > > using the library, but I don't think that's the right choice. > > > > I'd say it's a bug, this is clearly a contract, since the data being > > passed into the ctor can easily not be user input (i.e. it's most likely > > two literals that will never depend on a user). If it is user input, the > > caller of the ctor should enforce the user input before passing it to > > iota. > > You can't validate all user input, so external data ends up spead across > your entire application. So I don't understand obsession with -release > switch, because contracts most of the time do validate user input. If we > think about -release switch as a HP-hack for exotic code, there will be no > ideological difference between assert and enforce.
The idea is that if an assertion fails, there is a bug in your program. You _cannot_ rely on an assertion being run, because it could be compiled out. It is _only_ for verifying that your code is correct. Exceptions, on the other hand, are used for handling errors. If something which results in an error but which is _not_ a logic bug in your program, then it should be handled by an exception. User input would be a classic example of this. If you get bad user input, that's not the program's fault. It can verify that the user input is valid and then assume that it's valid after that (at which point, using assert would make sense, because it's supposed to be guaranteed that the values are valid, since they were validated). But in handling the user input, it would throw on error, not assert. enforce is merely a shorthand way of testing and throw exceptions on failure. It makes exception handling look like assertions. But it is an _entirely_ different thing. As has been point out, the problem is in cases where it's not clear whether you should treat input as user input (and therefore needs to _always_ be checked and have exceptions thrown on error) or whether you should treat input as being from your program and guaranteed to be valid (at which point you use assert to check that that guarantee actually holds). Assertions are _not_ for error handling. They _kill_ your program on failure (since they throw an Assert_Error_, not an exception). Exceptions (and therefore enforce) are for error handling. There is a _clear_ and _distinct_ difference between the two. The confusion is not between assert and enforce. The confusion is when you have a situation where whether assert or enforce is appropriate depends on how the function is being used. - Jonathan M Davis