Contract programming

John Colvin via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Dec 17 13:17:56 PST 2014


On Wednesday, 17 December 2014 at 21:07:12 UTC, Oleg wrote:
> Is this behavior normal or it's bug?
>
> [code]
>
> import std.stdio;
>
> class A
> {
>     float func( float x )
>     in
>     {
>         assert( x > 0 );
>         stderr.writeln( "A.func in block" );
>     }
>     body
>     {
>         stderr.writeln( "A.func body block" );
>         return x / 3;
>     }
> }
>
> class B : A
> {
>     override float func( float x )
>     in
>     {
>         assert( x < 10 );
>         stderr.writeln( "B.func in block" );
>     }
>     body
>     {
>         stderr.writeln( "B.func body block" );
>         return x * 3;
>     }
> }
>
> void main()
> {
>     auto a = new B;
>     auto v = a.func( 3.14 );
> }
>
> [output]
>
> A.func in block
> B.func body block
>
> In class B 'in' block not called, but if add 'out' block it 
> called both for A and B classes.

Only 1 of the in contracts must be satisfied and it appears that 
in this case the A.foo one was checked first. Seeing as it 
passed, there was no need to check the B.foo in contract. Imagine 
it as an OR of in contracts.

All out contracts must be satisfied, hence both must be run to 
check. Images it as an AND of the out contracts.

See http://dlang.org/contracts.html


More information about the Digitalmars-d-learn mailing list