# 重构手法之简化条件表达式【2】

• Consolidate Duplicate Conditional Fragments（合并重复的条件片段）
• Remove Control Flag（移除控制标记）

# 3Consolidate Duplicate Conditional Fragments（合并重复的条件片段）

## 范例

`class Deal{ public double Price { get; set; } private bool IsSpecialDeal() { //your code here return true; } private void Send() { //your code here } public double GetTotalPrice() { double total; if (IsSpecialDeal()) { total = Price * 0.95; Send(); } else { total = Price * 0.98; Send(); } return total; }}`

`class Deal{ public double Price { get; set; } private bool IsSpecialDeal() { //your code here return true; } private void Send() { //your code here } public double GetTotalPrice() { double total; if (IsSpecialDeal()) { total = Price * 0.95; } else { total = Price * 0.98; } Send(); return total; }}`

# 4Remove Control Flag（移除控制标记）

## 动机

set done to false

while not done

if(condition)

do something

set done to true

next step of loop

## 范例：以break取代简单的控制标记

`class Person{ public void CheckSecurity(string[] people) { bool found = false; foreach (var person in people) { if (!found) { if (person == "Don") { SendAlert(); found = true; } if (person == "John") { SendAlert(); found = true; } } } } private void SendAlert() { }}`

`class Person{ public void CheckSecurity(string[] people) { foreach (var person in people) { if (person == "Don") { SendAlert(); break; } if (person == "John") { SendAlert(); break; } } } private void SendAlert() { }}`

## 范例：以return返回控制标记

`class Person{ public void CheckSecurity(string[] people) { string found = string.Empty; foreach (var person in people) { if (found == string.Empty) { if (person == "Don") { SendAlert(); found = "Don"; } if (person == "John") { SendAlert(); found = "John"; } } } OtherMethod(found); } private void SendAlert() { } private void OtherMethod(string found) { }}`

`class Person{ public void CheckSecurity(string[] people) { string found = FoundMiscreant(people); OtherMethod(found); } private string FoundMiscreant(string[] people) { string found = string.Empty; foreach (var person in people) { if (person == "Don") { SendAlert(); found = "Don"; } if (person == "John") { SendAlert(); found = "John"; } } return found; } private void SendAlert() { } private void OtherMethod(string found) { }}`

`class Person{ public void CheckSecurity(string[] people) { string found = FoundMiscreant(people); OtherMethod(found); } private string FoundMiscreant(string[] people) { foreach (var person in people) { if (person == "Don") { SendAlert(); return "Don"; } if (person == "John") { SendAlert(); return "John"; } } return string.Empty; } private void SendAlert() { } private void OtherMethod(string found) { }}`

## 小结

To Be Continued……