如果我发现,对于一个field(值域),在其所驻class之外的另一个class中有更多函数使用了它,我就会考虑搬移这个field。
上述所谓「使用」可能是通过设值/取值(setting/getting)函数间接进行。我也可能移动该field的用户(某函数),这取决于是否需要保持接口不受变化。如果这些函数看上去很适合待在原地,我就选择搬移field。
Encapsulate Field封装值
将它封装起来。Self Encapsulate Field自动封装值
也许会有帮助下面是Account class的部分代码
class Account...private AccountType _type;private double _interestRate;double interestForAmount_days (double amount, int days) {return _interestRate * amount * days / 365;}
我想把表示利率的_interestRate搬移到AccountType class去。目前已有数个函数引用了它,interestForAmount_days() 就是其一。
下一步我要在AccountType中建立_interestRate field以及相应的访问函数:
class AccountType...// 在新类中创建属性private double _interestRate;// 创建属性对应的get和set方法void setInterestRate (double arg) {_interestRate = arg;}double getInterestRate () {return _interestRate;}
这时候我可以编译新的AccountType class。
现在,我需要让Account class中访问此_interestRate field的函数转而使用AccountType对象,然后删除Account class中的_interestRate field。
我必须删除source field,才能保证其访问函数的确改变了操作对象,因为编译器会帮我指出未正确获得修改的函数。
private double _interestRate;double interestForAmount_days (double amount, int days) {// 调用改为目标类中的属性return _type.getInterestRate() * amount * days / 365;}
使用Self Encapsulate(自我封装)
如果有很多函数已经使用了_interestRate field,我应该先运用Self Encapsulate Field
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变量_interestRate = arg;}private double getInterestRate () {// 多个位置使用了_interestRate变量return _interestRate;}
这样,在搬移field之后,我就只需要修改访问函数(accessors)就行了
double interestForAmountAndDays (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 使我得以保持小步前进。如果我需要对做许多处理,保持小步前进是有帮助的。特别值得一提的是:首先使用Self Encapsulate Field 使我得以更轻松使用Move Method 将函数搬移到target class中。如果待移函数引用了field的访问函数(accessors),那么那些引用点是无须修改的。
上一篇:python selenium自动化登录之验证码识别
下一篇:RTMPose