Contracts or Exceptions?
Steven Schveighoffer
schveiguy at yahoo.com
Tue Mar 29 11:49:25 PDT 2011
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.
-Steve
More information about the Digitalmars-d-learn
mailing list