用 Java 中的断言检查抽象方法行为(契约)是个好习惯吗?

问题描述 投票:0回答:1

我希望实现抽象方法以保持一些契约 例如

我有一个

Cells
抽象类,它是
Cell[]
的包装器,
Cells
抽象类具有抽象受保护方法
_initCells
,并且我声明了
initCells
finalpublic 使用断言检查
Cell[]
方法输出中的
_initCells
中是否不包含 duplicatesout-of-bounds 单元格的方法。 不管是国际象棋细胞还是棋子细胞。

但是默认情况下断言是禁用的,如果另一个包想要创建

Cells
的子类,程序员可以通过不启用断言来忽略契约。

如果我有一个接口而不是抽象类,我该如何执行合同?

编辑:

到目前为止,我决定在 System.err 中打印一条消息并从 initCells 方法调用 System.exit

java abstract-class assert assertion abstract-methods
1个回答
0
投票

默认情况下断言是禁用的,但例外情况则不会。如果此先决条件是一个重要的前提条件,或者如果不遵守可能会导致安全或安保问题,那么当您检测到不合格情况时,请提出

RuntimeException
或其子类之一。

public final initCells() {
  _initCells();
  if (containsDuplicates()) {
    throw new RuntimeException("Cells contain duplicates");
  }
  if (anyCellIsOutOfBounds()) {
    throw new RuntimeException("Cell is out of bounds");
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.