如果有很多函數已經使用了_interestRate field,我應該先運用Self Encapsulate Field(171):
class Account...
private AccountType _type;
private double _interestRate;
double interestForAmount_days(double amount, int days) {
return getInterestRate() * amount * days / 365;
}
private void setInterestRate(double arg) {
_interestRate = arg;
}
private double getInterestRate() {
return _interestRate;
}
這樣,在搬移field之后,我就只需要修改訪問函數就行了:
double interestForAmount_days(double amount, int days) {
return getInterestRate() * amount * days / 365;
}
private void setInterestRate(double arg) {
_type.setInterestRate(arg);
}
private double getInterestRate() {
return _type.getInterestRate();
}
如果以后有必要,我可以修改訪問函數(accessors)的用戶,讓它們使用新對象。Self Encapsulate Field(171)使我得以保持小步前進。如果我需要對class做許多處理,保持小步前進是有幫助的。特別值得一提的是:首先使用Self Encapsulate Field(171)使我得以更輕松使用Move Method(142)將函數搬移到target class中。如果待移函數引用了field的訪問函數(accessors),那么那些引用點是無須修改的。