如果有很多函數(shù)已經(jīng)使用了_interestRate field,我應(yīng)該先運(yùn)用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之后,我就只需要修改訪問(wèn)函數(shù)就行了:
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();
}
如果以后有必要,我可以修改訪問(wèn)函數(shù)(accessors)的用戶,讓它們使用新對(duì)象。Self Encapsulate Field(171)使我得以保持小步前進(jìn)。如果我需要對(duì)class做許多處理,保持小步前進(jìn)是有幫助的。特別值得一提的是:首先使用Self Encapsulate Field(171)使我得以更輕松使用Move Method(142)將函數(shù)搬移到target class中。如果待移函數(shù)引用了field的訪問(wèn)函數(shù)(accessors),那么那些引用點(diǎn)是無(wú)須修改的。