什么是监护人密码?

What is guardian code?

我的讲师开始在我们的阅读中提到一种叫做监护人代码的东西material。如果有帮助,这是一个 Java 初学者模块。下面是文中的一些引用。

Since there are no mutators and therefore no mutator guardian code the guardian code is forced into the constructor (as a call to the validateDate(…) private helper method). The constructor would usually call the mutators to check initial values received as constructor parameters were valid before assigning them their respective instance variables.

如有任何帮助,我们将不胜感激

谢谢!!

您的讲师可能指的是 保护代码。这增加了一个额外的防御验证层,以确保您接收或发送的数据在任何方面都不是无效的。通常,编写保护代码以确保他们需要的值不是 null(以防止 NullPointerException),或者在预期范围内——尽管这是对验证的更广泛讨论。

例如,如果我正在编写一个名为 boolean validateDate(Date date) 的方法,我将编写的一段保护代码是:

public boolean validateDate(Date date) {
    if(null == date) {
        throw new IllegalArgumentException("Date can't be null");
    }
    // other logic to follow
}

文中引用了提供参数验证的代码,"guarding"防止对象进入不良状态。

Fox 示例,如果您正在构建一个 class 和一个名为 serialNumberString 属性,它必须有七到九个字符长,您可以添加一个 setter 像这样:

void setSerialNumber(String sn) {
    if (sn == null || sn.length() < 7 || sn.length() > 9) {
        throw new IllegalArgumentException("sn");
    }
    serialNumber = sn;
}
上面代码片段中的

if是"guardian code"。教科书上说,当 class 可变时,此保护代码进入 setters。但是,当 class 不可变时,您将此代码移动到构造函数中:

MyObject(String sn) {
    if (sn == null || sn.length() < 7 || sn.length() > 9) {
        throw new IllegalArgumentException("sn");
    }
    serialNumber = sn;
}