Contracts or Exceptions?

spir denis.spir at gmail.com
Tue Mar 29 12:35:50 PDT 2011


On 03/29/2011 08:49 PM, Steven Schveighoffer wrote:
> On Tue, 29 Mar 2011 14:40:02 -0400, Mike Linford <mike.linford.reg at gmail.com>
> wrote:
>
>> Hello,
>>
>> So I'm writing a function for a library. It takes a struct as an
>> argument. The struct's fields can't just be any old values, though. The
>> function won't work if some of the fields are weird. It could return an
>> erroneous value, or even crash.
>>
>> The thing is, though, that I can't tell whether the best approach is to
>> use an in-contract or throw an exception if it doesn't pass my test. What
>> would you guys recommend?
>
> This has been discussed very recently on the main newsgroup (digitalmars.D). It
> is not an easy question to answer.
>
> There are two ways to answer it easily: 1. if the input to the function will
> always be deterministic, meaning there is no chance some environmental cause
> can affect the input, or the validity of the input, then use contracts, this
> should catch any code errors during testing. 2. if the input to the function
> will always be generated external to the program (i.e. from a file), then you
> should use exceptions.
>
> If it could be either, there are different schools of thought on this. If the
> function isn't performance critical, throwing an exception is likely a good
> choice. However, if it is performance critical, I'd recommend using contracts.
> Then if you have a situation when your input is externally generated, you need
> to check it outside the function with an exception thrown on error.

... or users of your service should be warned it is their reponsability to 
check validity of inputs to it (case of a lib).

Denis
-- 
_________________
vita es estrany
spir.wikidot.com



More information about the Digitalmars-d-learn mailing list