How do I use in contract with interface?

Jonathan M Davis newsgroup.d at jmdavisprog.com
Wed Nov 15 15:39:14 UTC 2017


On Wednesday, November 15, 2017 10:14:32 Steven Schveighoffer via 
Digitalmars-d-learn wrote:
> On 11/15/17 9:43 AM, Dr. Assembly wrote:
> > I'm learning to use interface with contracts. In below code, in isn't
> > being "called". Can someone point out why? what am I doing wrong?
> >
> > void main() {
> >
> >      C c = new C();
> >      writeln(c.foo(1));
> >
> > }
> >
> > interface I
> > {
> >
> >      int foo(int i)
> >          in { assert(i > 2); }
> >          out (result) { assert(result != 0); }
> >
> >      void baa();
> >
> > }
> >
> > class C : I
> > {
> >
> >      int foo(int i) {
> >          return i * 2;
> >      }
> >
> >      void baa() {
> >          writeln("Hello!");
> >      }
> >
> > }
>
> Not going to defend these design decisions, but according to
> https://dlang.org/spec/contracts.html#in_out_inheritance:

Well, the rules do make sense when you consider that it can make sense for a
function to allow arguments that the base class didn't. The in contract is
essentially saying what the function can validly operate on, and there's no
reason why a derived class couldn't work with more values than the base
class could. So, the loosening makes sense when you think about it. It just
means that if you're trying to have a contract that you put in one place and
then gets reused rather than having to repeat it in each derived class, then
in contracts don't really work. For that, it makes more sense to use NVI so
that the in contract is on the public base class or interface function, and
the protected, derived functions that the public function calls then don't
actually have any in contracts.

Either way, I don't think that many would argue that the &&ing of the out
contracts is problematic.

Regardless, the rules that we have come from languages that are far more
into contract rules than we are. So, it's not like we made them up.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list