How do I use in contract with interface?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Nov 15 15:47:36 UTC 2017


On Wednesday, November 15, 2017 10:33:50 Steven Schveighoffer via 
Digitalmars-d-learn wrote:
> On 11/15/17 10:14 AM, Jonathan M Davis wrote:
> >  So, it's pointless to put an in contract on an
> >
> > interface's function unless you're trying to ensure that nothing in
> > derived contracts is any stricter than that contract, which in practice
> > likely means that it's pointless to put an in contract on an interface
> > function.
> Just tested this, and actually, if you put no contract on an interface
> function, it negates any contracts on the implementing functions. So
> there definitely is a use for the in contract on an interface -- if you
> plan on defining contracts on implementing types.
>
> I'm curious why the absence of an in contract disables all other in
> contracts. I would have expected it to simply have no effect.

The issue is that if _any_ in contract passes, then they all pass, and the
lack of an in contract is the same as a contract that always passes. So, I
guess that if you're trying to put contracts on your derived classes, the in
contract on the interface function isn't really pointless, but it really
doesn't have the desired effect. Basically, once you have any class or
interface in the inheritance chain, you have to put in contracts on _all_ of
them if you want them to have any effect - and whichever one is the loosest
is the one that's going to really matter.

All in all, I expect that in most cases, using NVI with an in contract on
the public function would be much closer to what folks would be looking for.
The way that in contracts work with inheritance makes sense in principle,
but it does tend to make them kind of useless in practice.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list