On Wed, 16 Jun 2010 06:55:21 -0400, Steven Schveighoffer wrote: > 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"
It also adds a file and a line number to the error message, so the problem is easier to track down. Very handy. :) > And in fact, I think there's an errnoEnforce which throws a standard > exception with the string error from the system. That's right, and there's even an enforceEx() which lets you specify which exception type to throw: http://digitalmars.com/d/2.0/phobos/std_contracts.html#enforceEx -Lars
