Lutger 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'd think of it this way: enforce() is part of defensive programming, and > contracts are related to software testing.
That's probably a pretty good way of putting it. It's essentially the difference between when you use assertions and when you use exceptions. Assertions assert that something is _always_ true and that if it isn't, the program is wrong, while exceptions are for exceptional circumstances (as opposed to _never_) and indicate an error of some kind which is likely outside the control of the program - such as something happening with the file system, user input, or the amount of available memory. enforce() appears to effectively be the exception equivalent to assert(). You use it when you want an exception thrown rather than when you want to kill your program due to an error. Unfortunately, the difference between when assertions should be used and when exceptions should be used is one that is just subtle enough that it often trips people up, even though in theory it should be fairly straightforward. - Jonathan M Davis
