When I override functions in D with "in" contracts, then the inherited "in" contracts are checked. If they fail, then the overridden "in" contracts are checked. If I don't specify any in contract, then it is interpreted as if there is an empty "in" contract. So the following code compiles and runs successfully.
module main;
import std.stdio;
interface I
{
void write( int i )
in
{
assert( i > 0 );
}
}
class C : I
{
void write( int i )
{
writeln( i );
}
}
int main()
{
I i = new C;
i.write( -5 );
getchar();
return 0;
}
I only want the precondition of I.write()
to be checked when I call i.write()
since that is what is statically known to be sufficient for I.write()
to run correctly by the compiler. Checking all preconditions after dynamic dispatch strikes me as odd from an OO perspective since encapsulation is lost.
I could repeat the precondition or write in { assert( false ); }
in all classes implementing the interface, but that's a pain. Is that a design error in the D language? Or is there any proper scalable way to do that?