gpt4 book ai didi

interface - 如何在 D 接口(interface)中有意义地使用前置条件契约?

转载 作者:行者123 更新时间:2023-12-04 20:50:05 24 4
gpt4 key购买 nike

当我用“in”契约(Contract)覆盖 D 中的函数时,会检查继承的“in”契约(Contract)。如果它们失败,则检查覆盖的“in”契约(Contract)。如果我没有在契约(Contract)中指定任何内容,则将其解释为好像有一个空的“in”契约(Contract)。所以下面的代码编译运行成功。

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.write()的前提条件当我调用 i.write() 时进行检查因为这对于 I.write() 来说是静态已知的就足够了。由编译器正确运行。从 OO 的角度来看,在动态调度之后检查所有先决条件让我觉得很奇怪,因为封装丢失了。

我可以重复前提条件或写 in { assert( false ); }在所有实现接口(interface)的类中,但这很痛苦。这是D语言的设计错误吗?还是有任何适当的可扩展方式来做到这一点?

最佳答案

http://dlang.org/dbc.html

If a function in a derived class overrides a function in its super class, then only one of the in contracts of the function and its base functions must be satisfied. Overriding functions then becomes a process of loosening the in contracts.

A function without an in contract means that any values of the function parameters are allowed. This implies that if any function in an inheritance hierarchy has no in contract, then in contracts on functions overriding it have no useful effect.

Conversely, all of the out contracts needs to be satisfied, so overriding functions becomes a processes of tightening the out contracts.


当多态行为受到质疑时,这实际上是一个困难的设计难题。例如,查看这个带有相关长篇讨论的错误报告: http://d.puremagic.com/issues/show_bug.cgi?id=6857
关于如何实现想要的行为的问题 - 当需要防止复制粘贴时,mixin 总是有效的,但我不确定从按契约(Contract)设计范式的角度来看是否可以。不幸的是,需要有人在这个问题上更有能力的建议。

关于interface - 如何在 D 接口(interface)中有意义地使用前置条件契约?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11682991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com