31天重构指南之二:移动方法
2009-09-15 17:16
549 查看
今天的重构指南是关于移动方法的,移动方法是一个简单却容易被忽略的重构,正如它的名字所表达的意思一样,移动方法就是将方法移动到合适的位置。让我们来看下面的待重构代码:
原文链接:http://www.lostechies.com/blogs/sean_chambers/archive/2009/08/02/refactoring-day-2-move-method.aspx
1: public class BankAccount
2: {
3: public BankAccount(int accountAge, int creditScore, AccountInterest accountInterest)
4: {
5: AccountAge = accountAge;
6: CreditScore = creditScore;
7: AccountInterest = accountInterest;
8: }
9:
10: public int AccountAge { get; private set; }
11: public int CreditScore { get; private set; }
12: public AccountInterest AccountInterest { get; private set; }
13:
14: public double CalculateInterestRate()
15: {
16: if (CreditScore > 800)
17: return 0.02;
18:
19: if (AccountAge > 10)
20: return 0.03;
21:
22: return 0.05;
23: }
24: }
25:
26: public class AccountInterest
27: {
28: public BankAccount Account { get; private set; }
29:
30: public AccountInterest(BankAccount account)
31: {
32: Account = account;
33: }
34:
35: public double InterestRate
36: {
37: get { return Account.CalculateInterestRate(); }
38: }
39:
40: public bool IntroductoryRate
41: {
42: get { return Account.CalculateInterestRate() < 0.05; }
43: }
44: }
上面代码中让我们感兴趣的是BankAccount.CalculateInterest方法,我们需要对它进行重构,重构的提示是我们需要将方法定义在对它使用最多的类中。在这个例子中,我们要将
BankAccount.CalculateInterest方法移动到AccountInterest类中。重构后的代码如下:
1: public class BankAccount
2: {
3: public BankAccount(int accountAge, int creditScore, AccountInterest accountInterest)
4: {
5: AccountAge = accountAge;
6: CreditScore = creditScore;
7: AccountInterest = accountInterest;
8: }
9:
10: public int AccountAge { get; private set; }
11: public int CreditScore { get; private set; }
12: public AccountInterest AccountInterest { get; private set; }
13: }
14:
15: public class AccountInterest
16: {
17: public BankAccount Account { get; private set; }
18:
19: public AccountInterest(BankAccount account)
20: {
21: Account = account;
22: }
23:
24: public double InterestRate
25: {
26: get { return CalculateInterestRate(); }
27: }
28:
29: public bool IntroductoryRate
30: {
31: get { return CalculateInterestRate() < 0.05; }
32: }
33:
34: public double CalculateInterestRate()
35: {
36: if (Account.CreditScore > 800)
37: return 0.02;
38:
39: if (Account.AccountAge > 10)
40: return 0.03;
41:
42: return 0.05;
43: }
44: }
原文链接:http://www.lostechies.com/blogs/sean_chambers/archive/2009/08/02/refactoring-day-2-move-method.aspx
相关文章推荐
- 31天重构指南之四:降低方法(pull down)
- 《31天重构》2:移动方法
- 31天重构指南之十三:提取方法对象
- 31天重构指南之十:提取方法
- 31天重构学习笔记2. 移动方法
- 31天学习重构(java)---2. 移动方法
- 31天重构学习笔记2. 移动方法
- 31天重构指南之二十八:为布尔方法命名
- 31天重构指南之二十二:分解方法
- 31天重构学习笔记2. 移动方法
- 31天重构指南之三: 提升方法(pull up )
- 31天重构学习笔记2. 移动方法
- 31天重构学习笔记4. 降低方法
- 重构-改善既有代码的设计:对象之间移动特性的八种方法(五)
- 31天重构指南之二十七:去除上帝类
- 31天重构指南之九:提取接口
- 31天重构学习笔记3. 提升方法
- 31天重构学习笔记22. 分解方法
- 31天重构学习笔记28. 为布尔方法命名
- 31天重构学习笔记7. 重命名(方法,类,参数)