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

时间:2022-05-14 07:22:07

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

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

 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 关键字来修饰,表示只能被自身和子类使用。重构其实就这么简单。