一、Remove Control Flag(移除控制标记)
动机(Motivation)
以break语句或return语句取代控制标记。
示例
01 |
public void CheckSecurity(string[] people) |
03 |
string found = string.Empty; |
04 |
for (int i = 0; i < people.Length; i++) |
08 |
if (people[i].Equals("Don")) |
12 |
if (people[i].Equals("John")) |
改为
01 |
public void CheckSecurity(string[] people) |
03 |
string found = string.Empty; |
04 |
for (int i = 0; i < people.Length; i++) |
08 |
if (people[i].Equals("Don")) |
13 |
if (people[i].Equals("John")) |
示例
01 |
public string FindPeople(string[] people) |
03 |
string found = string.Empty; |
04 |
for (int i = 0; i < people.Length; i++) |
08 |
if (people[i].Equals("Don")) |
12 |
if (people[i].Equals("John")) |
改为
01 |
public string FindPeople(string[] people) |
03 |
string found = string.Empty; |
04 |
for (int i = 0; i < people.Length; i++) |
08 |
if (people[i].Equals("Don")) |
12 |
if (people[i].Equals("John")) |
二、Replace Nested Conditional with Guard Clauses(以卫语句取代嵌套条件式)
动机(Motivation)
使用卫语句(guard clauses)表现所有特殊情况。
示例
01 |
public double GetPayAmount() |
05 |
result = DeadAmount(); |
09 |
result = SeparatedAmount(); |
13 |
result = RetiredPayAmount(); |
15 |
result = NormalPayAmount(); |
改为
01 |
public double GetPayAmount() |
06 |
return SeparatedAmount(); |
08 |
return RetiredPayAmount(); |
09 |
return NormalPayAmount(); |
三、Introduce Null Object (引入Null对象)
动机(Motivation)
将null value(无效值)替换为null object(无效物)
示例
2 |
plan = BillingPlan.Basic(); |
4 |
plan = customer.GetPlan(); |
改为
1 |
public double GetPayAmount() |
4 |
plan = BillingPlan.Basic(); |
6 |
plan = customer.GetPlan(); |
四、Rename Method(重新命名函数)
动机(Motivation)
修改函数名称让它人容易理解它的作用
示例
1 |
public int Getinvcdtlmt() |
改为
1 |
public int GetInvoiceAbleCreditLimit() |
五、Separate Query from Modifier(将查询函数和修改函数分离)
动机(Motivation)
建立两个不同的函数,其中一个负责查询,另一个负责修改。
示例
01 |
public string FindPeople(string[] people) |
03 |
string found = string.Empty; |
04 |
for (int i = 0; i < people.Length; i++) |
08 |
if (people[i].Equals("Don")) |
13 |
if (people[i].Equals("John")) |
改为
01 |
public string FindPeople(string[] people) |
03 |
string found = FindPeopleOne(people); |
04 |
SendMailToPeople(found); |
07 |
public string FindPeopleOne(string[] people) |
09 |
string found = string.Empty; |
10 |
for (int i = 0; i < people.Length; i++) |
14 |
if (people[i].Equals("Don")) |
18 |
if (people[i].Equals("John")) |
27 |
public void SendMailToPeople(string people) |
29 |
if (!string.IsNullOrEmpty(people)) |
六、Parameterize Method(令函数携带参数)
动机(Motivation)
建立单一函数,以参数表达那些不同的值
示例
1 |
public double TenPercentRaise() |
6 |
public double FivePercentRaise() |
改为
1 |
public double Raise(double factor) |
3 |
return salary * factor; |
七、Replace Parameter with Explicit Methods(以明确函数取代参数)
动机(Motivation)
针对该参数的每一个可能值,建立一个独立函数。
示例
04 |
public void SetValue(string name, int value) |
06 |
if (name.Equals("height")) |
11 |
if (name.Equals("width")) |
改为
06 |
set { _height = value; } |
11 |
set { _width = value; } |