On Saturday, February 24, 2018 04:33:52 psychoticRabbit via Digitalmars-d-
learn wrote:
> On Saturday, 24 February 2018 at 04:22:12 UTC, Jonathan M Davis
> wrote:
> > Why is there anything dodgy going on and why would you need
> > contracts? Contracts actually tend to go very badly with
> > generic code, because whatever they assert has to be generic,
> > and while that works sometimes, more often than not, it doesn't.
> >
> > - Jonathan M Davis
> what if 3.3 is passed to the template, and it explicately casts
> it to an int.
> To me, that would be dodgy

It could be exactly how the function is intended to work, since that's how
casting to int works for float. And there's nothing dodgy about a cast from
float to int losing the part of the value to the right of the decimal place.
That's the expected behavior.

> - unless there was a contract, that I
> had accepted and agreed to, so that this not dodgy.

All contracts are are assertions. That's it. There's nothing special about
them. An in contract is used to verify that the function is given valid
data, but there really isn't any accepting or agreeing to a contract.
Rather, it's something that blows up in your face if you give it bad data so
that you can catch bugs. Presumably, the documentation gives the
requirements for the function if it has them, and then an in contract can be
used to verify that the arguments don't violate those requirements, but all
it is is a tool for catching bugs.

And there isn't necesarily anything buggy about casting 3.3 to an int. That
depends entirely on what the code is supposed to be doing.

Now, by having the function simply accept int you avoid the entire question,
because then it's up to the caller to decide how they go about converting to
int, and I'd argue that that's better in general, but there are times when
casting within the function may make more sense.

- Jonathan M Davis

Reply via email to