Improve "Improve Contract Syntax" DIP 1009

H. S. Teoh hsteoh at quickfur.ath.cx
Sat Nov 4 15:43:29 UTC 2017


On Sat, Nov 04, 2017 at 09:38:42AM -0600, Jonathan M Davis via Digitalmars-d wrote:
> On Saturday, November 04, 2017 15:27:39 Ola Fosheim Grøstad via Digitalmars-
> d wrote:
> > On Saturday, 4 November 2017 at 14:12:08 UTC, Adam D. Ruppe wrote:
> > > On Saturday, 4 November 2017 at 13:59:39 UTC, Jonathan M Davis
> > >
> > > wrote:
> > >> I'm very much of the opinion that proper unit tests pretty
> > >> much eliminate the need for out contracts.
> > >
> > > I think that sqrt example is just bad. Out contracts shouldn't
> > > be testing specific values, but rather ranges or nullness or
> > > other such things that arguably should be part of the return
> > > type, but just don't fit in the type system for whatever reason.
> >
> > No, Jonathan is correct. The postcondition should be able to
> > access values as they were stated in the precondition.
> 
> In principle, that would be nice, but in practice, it's not really
> feasible.  In the general case, there's no way to save the state of
> the parameter at the beginning of the function call (you could with
> some types, but for many types, you couldn't). IIRC, it's been
> discussed quite a bit in the past, and there are just too many
> problems with it.
[...]

This isn't as bad as it sounds. If you really cared for out-contracts
being able to access the original state of the parameters, just make the
parameters const.  In the cases where you can't make them const,
out-contracts are probably impractical anyway -- independently of how D
implements them, if your function is going to mutate parameters then the
only way the out-contract would work is if a copy of the parameters were
made.  But if you're already going to do that, might as well just make
the parameters const and do the copy inside the function body.

But as Adam said, out-contracts aren't really intended for semantic
enforcement, but they are more like extensions of the type system. E.g.,
asserting that a returned pointer is never null, or that a returned
value is never negative, or stays within some range of values, etc..
Basically, stuff the caller can assume about the return value as far as
the set of possible values is concerned.  For most non-trivial
functions, semantic enforcement requires you to basically reimplement
the function body, which is kinda pointless.  If you want semantic
enforcement, that's what unittests are for.


T

-- 
Caffeine underflow. Brain dumped.


More information about the Digitalmars-d mailing list