您的位置:首页 > 其它

重构第5天:提升字段(Pull Up Field)

2016-03-16 22:07 399 查看
理解:提升字段和前面讲解的方法提公很类似,可以说方式都是一样的。就是把继承类中经常用到的字段,提出来 放到基类中,达到通用的目的。提高代码重用性和可维护性。

详解:如下重构前的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _31DaysRefactor
{

public abstract class Account
{

}

public class CheckingAccount : Account
{
private decimal _minimumCheckingBalance = 5m;
}

public class SavingsAccount : Account
{

private decimal _minimumCheckingBalance = 5m;
}
}


从代码乐意看出,Account类的继承类CheckingAccount和SavingsAccount都有一个相同的字段_minimumCheckingBalance ,为了提高易用性和可维护性,我们把_minimumCheckingBalance 字段提出来放到基类Account中去。

重构后的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace _31DaysRefactor
{

public abstract class Account
{
protected decimal _minimumCheckingBalance = 5m;
}

public class CheckingAccount : Account
{

}

public class SavingsAccount : Account
{

}
}


注意提到公共基类中,最好用 protected 关键字来修饰,表示只能被自身和子类使用。重构其实就这么简单。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: