On Wed, 16 Jun 2010 05:28:46 -0400, Ary Borenszweig <[email protected]> wrote:

On 06/16/2010 04:15 PM, Walter Bright wrote:
Ali Çehreli wrote:
bearophile wrote:
I have counted about 200 usages of std.contracts.enforce() inside
Phobos. Can you tell me what's the purpose of enforce() in a language
that has built-in Contract Programming?

I can see two benefits:

The difference is not based on those 3 points, but on what Andrei wrote
here. Contracts and error checking are completely distinct activities
and should not be conflated.

Could you please explain them? There are many people here that don't understand the difference between these two concepts (including me). So maybe we are too dumb, maybe those concepts are not generally known or maybe the explanation is not very well clear in the documentation.

I think of enforce as a convenient way translating an error in an expectation to an exception in a single expression.

For example, take some system call that returns -1 on error, you could do this:

if(result < 0)
   throw new Exception("oops!");

or you could do this:

enforce(result >= 0, "oops!");

Think of enforce as "throw if"

And in fact, I think there's an errnoEnforce which throws a standard exception with the string error from the system.

I'd say the difference between enforce and assert is exactly what Andrei said -- enforce is meant to catch errors that can occur during normal operation. Assert is meant to catch errors that are not expected during normal operation. Assert's more like a sanity check. Also, assert is turned off in release mode, enforce is left on.

-Steve


Reply via email to