一、Preserve Whole Object(保持对象完整)
动机(Motivation)
要向某个方法内传递若干个值,可以改使用传递整个对象。
示例
int low = DaysTempRange().GetLow();
int high = DaysTempRange().GetHigh();
withinPlan = Plan.WithinRange(low, high);
改为
withinPlan = Plan.WithinRange(DaysTempRange());
二、Replace Parameter with Methods(以函数取代参数)
动机(Motivation)
对象调用某个函数,并将所得结果作为参数,传递给另一个函数。而接收该参数的函数应直接调用该函数。
示例
public double GetPrice()
{
int basePrice = _quantity * _itemPrice;
double discountLevel = GetDiscountLevel();
double finalPrice = DiscountedPrice(basePrice, discountLevel);
}
private double DiscountedPrice(int basePrice, double discountLevel)
{
}
改为
public double GetPrice()
{
int basePrice = _quantity * _itemPrice;
double finalPrice = DiscountedPrice(basePrice);
}
private double DiscountedPrice(int basePrice)
{
double discountLevel = GetDiscountLevel();
}
三、Introduce Parameter Object(引入参数对象)
动机(Motivation)
以一个对象取代这些参数。
示例
public string GetUserInfo(int ID, string name, string age, string sex)
{
}
改为
public string GetUserInfo(User user)
{
}
public class User
{
public int ID { get; set; }
public int Name { get; set; }
public int Age { get; set; }
public int Sex { get; set; }
}
四、Remove Setting Method(移除设值函数)
动机(Motivation)
去掉该值域的所有设置函数(setter),class中的某个值域,应该在对象初创时被设值,然后就不再改变。
示例
public class Account
{
private string _ID;
public Account(string id)
{
SetID(id);
}
private void SetID(string id)
{
_ID = id;
}
}
改为
public class Account
{
private string _ID;
public Account(string id)
{
_ID = id;
}
}
五、Hide Method(隐藏某个函数)
动机(Motivation)
一个函数,从来没有被其它任何class用到,将这个class改为private。
示例
public string GetUserInfo(User user)
{
return null;
}
改为
private string GetUserInfo(User user)
{
return null;
}
六、Replace Constructor with Factory Method(以工厂函数取代构造函数)
动机(Motivation)
在创建对象时不仅仅是对它做简单的建构动作(simple construction),将constructor(构造函数)替换为factory method(工厂函数)
示例
public Account(string id)
{
_ID = id;
}
改为
public static Account Create(string id)
{
return new Account(id);
}
七、Encapsulate Downcast(封装[向下转型]动作)
动机(Motivation)
某个函数返回的对象,需要由函数调用者执行[向下转型](downcast)动作。
示例
public object LastReading()
{
return Readings.LastElement();
}
改为
public Reading LastReading()
{
return (Reading)Readings.LastElement();
}
八、Replace Error Code with Exception(以异常取代错误码)
动机(Motivation)
某个函数返回一个特定的代码(special code),用以表示某种错误情况。
示例
private int _balance;
public int Withdraw(int amount)
{
if (amount > _balance)
return -1;
else
{
_balance -= amount;
return 0;
}
}
改为
private int _balance;
public int Withdraw(int amount)
{
if (amount > _balance)
throw new Exception("error");
_balance -= amount;
}
步步为营 .NET 代码重构学习笔记系列
步步为营 .NET 代码重构学习笔记 二、提炼方法(Extract Method)
步步为营 .NET 代码重构学习笔记 三、内联方法(Inline Method)
步步为营 .NET 代码重构学习笔记 四、临时变量(Temporary Variable)
步步为营 .NET 代码重构学习笔记 五、分解函数和替换算法(Replace Method And Substitute Algorithm)