我希望实现抽象方法以保持一些契约 例如
我有一个
Cells
抽象类,它是Cell[]
的包装器,Cells
抽象类具有抽象受保护方法_initCells
,并且我声明了initCells
final和public
使用断言检查 Cell[]
方法输出中的 _initCells
中是否不包含 duplicates 和 out-of-bounds 单元格的方法。
不管是国际象棋细胞还是棋子细胞。
但是默认情况下断言是禁用的,如果另一个包想要创建
Cells
的子类,程序员可以通过不启用断言来忽略契约。
如果我有一个接口而不是抽象类,我该如何执行合同?
编辑:
到目前为止,我决定在 System.err 中打印一条消息并从 initCells 方法调用 System.exit
默认情况下断言是禁用的,但例外情况则不会。如果此先决条件是一个重要的前提条件,或者如果不遵守可能会导致安全或安保问题,那么当您检测到不合格情况时,请提出
RuntimeException
或其子类之一。
public final initCells() {
_initCells();
if (containsDuplicates()) {
throw new RuntimeException("Cells contain duplicates");
}
if (anyCellIsOutOfBounds()) {
throw new RuntimeException("Cell is out of bounds");
}
}