enforce()?

Leandro Lucarella luca at llucax.com.ar
Wed Jun 16 07:08:06 PDT 2010


Steven Schveighoffer, el 16 de junio a las 06:55 me escribiste:
> On Wed, 16 Jun 2010 05:28:46 -0400, Ary Borenszweig
> <ary at esperanto.org.ar> 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"

So maybe throw_if() would be a better name =)

Anyway, I think enforce() is poisson, because it make the programmer to
not think about errors at all, just add and enforce() and there you go.
But when you need to be fault tolerant, is very important to know what's
the nature of the error, but thanks to enforce(), almost every error is
a plain Exception, no hierarchy, no extra info, all you can do to get
a little more info about what happened is to parse the exception string,
and that's not really an option.

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

That's the only useful case of enforce, because it includes the
*important* information (the actual errno).

There is also enforceEx!(), to use a custom exception, which practically
nobody uses (I counted only 4 uses in phobos).

-- 
Leandro Lucarella (AKA luca)                     http://llucax.com.ar/
----------------------------------------------------------------------
GPG Key: 5F5A8D05 (F8CD F9A7 BF00 5431 4145  104C 949E BFB6 5F5A 8D05)
----------------------------------------------------------------------
Y será el día en que la electricidad deje de ser rayo y sea depilador
femenino.
	-- Ricardo Vaporeso


More information about the Digitalmars-d mailing list