June 15, 2012
On Friday, June 15, 2012 19:31:58 bearophile wrote:
> Jonathan M Davis:
> > It's the fact that enforce is lazy which prevents inlining
> > (which really does
> > need to be fixed or enforce is going to continue to be a
> > performance problem).
> 
> Then my "solution" solves nothing. Thank you Jonathan.
> 
> > However, this suggestion is clearly bad, because it's
> > suggesting turning an
> > exception into an assertion, which is _very_ broken thing to
> > do. Assertions
> > and exceptions are two _very_ different things and should be
> > treated as such.
> 
> enforce() sometimes is used as an assert you can't disable (as in
> Nullable.get, I think). So maybe such cases are better handled
> introducing two levels of asserts, "light asserts" and "strong
> asserts".

No. enforce and assert are fundamentaly different. One is used for throwing an exception, which indicates an error that occurs while running the program, whereas the other one throws an AssertError in non-release mode, which indicates a bug in the program. enforce should be used purely for error handling, and assert should be used purely for checking the validity of your code.

Pretty much the only case where it's really a question of whether one or the other should be used is when determining whether a function should be using design-by-contract or defensive programming. If it's design-by-contract, then failing the condition of the contract is a bug, and an assertion is used. If it's defensive programming, then the function treats its parameters as if they were user input, verifies them, and then throws if the conditions aren't met, thereby indicating an error condition to the caller. The choice between the two is a matter of whether the function treats its input as user input or not.

In the case of std.typecons.Nullable, it's treating its state as something relating to the program's input such that it is not necessarily a bug in the program if it attempts to get Nullable's value when it's null. So, the programmer does not need to check whether the Nullable is null or not before using it if they don't want to. If it were using assert, then it would be saying that programmer must guarantee that its state is not null before its value is fetched, or it's a bug. The two approaches mean fundamentally different things to how Nullable is designed and used.

- Jonathan M Davis
1 2
Next ›   Last »