在某些领域对象的方法中,他们没有直接使用属性,而是使用get方法。为什么呢一个例子如下:
private List<String> errorCodeList = new ArrayList<String>();
/**
* Add all errors to the error list.
*/
public void addAllErrors(Collection<String> theErrorStrings) {
if (errorCodeList == null) {
errorCodeList = new ArrayList<String>();
}
for (String aString: theErrorStrings) {
getErrorCodeList().add(aString);
}
}
/**
* @return the errorCodes
*/
public List<String> getErrorCodeList() {
return errorCodeList;
}
/**
* Set the error strings.
*/
public void setErrorCodeList(List<String> allErrors) {
this.errorCodeList = allErrors;
}
最佳答案
这是封装问题。通过仅通过getter和setter提供对实例变量的访问,您可以隐藏内部表示。这样,您便可以在以后修改实现而无需修改接口。您可能会决定使用HashMap来存储错误代码(无论出于何种原因)会更方便(一旦更改),访问该字段的所有代码都会中断。但是,如果提供了getter和setter,则尽管内部表示已更改,也可以将其保持不变。
此外,更容易确保不变式保持在适当的位置,如果每个人都可以访问这些字段,则无法做到这一点。