我想添加到其他答案中,可以使用setter防止对象处于无效状态。
例如,假设我们必须设置一个建模为String的TaxId。setter的第一个版本可以如下:
private String taxId;
public void setTaxId(String taxId) {
this.taxId = taxId;
}
但是,我们最好防止使用无效的taxId设置对象,因此我们可以进行检查:
private String taxId;
public void setTaxId(String taxId) throws IllegalArgumentException {
if (isTaxIdValid(taxId)) {
throw new IllegalArgumentException("Tax Id '" + taxId + "' is invalid");
}
this.taxId = taxId;
}
下一步,要改善程序的模块化,是使TaxId本身成为一个对象,能够对其进行检查。
private final TaxId taxId = new TaxId()
public void setTaxId(String taxIdString) throws IllegalArgumentException {
taxId.set(taxIdString); //will throw exception if not valid
}
同样对于获取者,如果我们还没有价值怎么办?也许我们想走一条不同的道路,我们可以这样说:
public String getTaxId() throws IllegalStateException {
return taxId.get(); //will throw exception if not set
}