### Remove Control Flag(移除控制標記)
在一系列布爾表達式(boolean expressions)中,某個變量帶有「控制標記」(control flag)的作用。
以break 語句或return 的語句取代控制標記。
**動機(Motivation)**
在一系列條件表達式中,你常常會看到「用以判斷何時停止條件檢查」的控制標記(control flag):
~~~
set done to false
while not done
if (condition)
do something
set done to true
next step of loop
~~~
這樣的控制標記帶來的麻煩超過了它所帶來的便利。人們之所以會使用這樣的控制標記,因為結構化編程原則告訴他們:每個子程序(routines)只能有一個入口(entry) 和一個出口(exit)。我贊同「單一入口」原則(而且現代編程語言也強迫我們這樣做),但是「單一出口」原則會讓你在代碼中加入討厭的控制標記,大大降低條件表達式的可讀性。這就是編程語言提供break 語句和continue 語句的原因:你可以用它們跳出復雜的條件語句。去掉控制標記所產生的效果往往讓你大吃一驚:條件語句真正的用途會清晰得多。
**作法(Mechanics)**
對控制標記(control flags)的處理,最顯而易見的辦法就是使用Java 提供的break 語句或continue 語句。
- 找出「讓你得以跳出這段邏輯」的控制標記值。
- 找出「將可跳出條件式之值賦予標記變量」的那個語句,代以恰當的break 語句或continue 語句。
- 每次替換后,編譯并測試。
在未能提供break 和continue 語句的編程語言中,我們可以使用另一種辦法:
- 運用Extract Method,將整段邏輯提煉到一個獨立函數中。
- 找出「讓你得以跳出這段邏輯」的那些控制標記值。
- 找出「將可跳出條件式之值賦予標記變量」的那個語句,代以恰當的return 語句。
- 每次替換后,編譯并測試。
即使在支持break 和continue 語句的編程語言中,我通常也優先考慮上述第二方案。因為return 語句可以非常清楚地表示:不再執行該函數中的其他任何代碼。 如果還有這一類代碼,你早晚需要將這段代碼提煉出來。
請注意標記變量是否會影響這段邏輯的最后結果。如果有影響,使用break 語句之后你還得保留控制標記值。如果你已經將這段邏輯提煉成一個獨立函數,也可以將控制標記值放在return 語句中返回。
**范例:以break 取代簡單的控制標記**
下列函數用來檢查一系列人名之中是否包含兩個可疑人物的名字(這兩個人的名字硬編碼于代碼中〕:
~~~
void checkSecurity(String[] people) {
boolean found = false;
for (int i = 0; i < people.length; i++) {
if (! found) {
if (people[i].equals ("Don")){
sendAlert();
found = true;
}
if (people[i].equals ("John")){
sendAlert();
found = true;
}
}
}
}
~~~
這種情況下很容易找出控制標記:當變量found 被賦予true 時,搜索就結束。我可以逐一引入break 語句:
~~~
void checkSecurity(String[] people) {
boolean found = false;
for (int i = 0; i < people.length; i++) {
if (! found) {
if (people[i].equals ("Don")){
sendAlert();
break;
}
if (people[i].equals ("John")){
sendAlert();
found = true;
}
}
}
}
~~~
最后獲得這樣的成功:
~~~
void checkSecurity(String[] people) {
boolean found = false;
for (int i = 0; i < people.length; i++) {
if (! found) {
if (people[i].equals ("Don")){
sendAlert();
break;
}
if (people[i].equals ("John")){
sendAlert();
break;
}
}
}
}
~~~
然后我就可以把對控制標記的所有引用去掉:
~~~
void checkSecurity(String[] people) {
for (int i = 0; i < people.length; i++) {
if (people[i].equals ("Don")){
sendAlert();
break;
}
if (people[i].equals ("John")){
sendAlert();
break;
}
}
}
~~~
**范例:以return 返回控制標記**
本項重構的另一種形式將使用return 語句。為了闡述這種用法,我把前面的例子稍加修改,以控制標記記錄搜索結果:
~~~
void checkSecurity(String[] people) {
String found = "";
for (int i = 0; i < people.length; i++) {
if (found.equals("")) {
if (people[i].equals ("Don")){
sendAlert();
found = "Don";
}
if (people[i].equals ("John")){
sendAlert();
found = "John";
}
}
}
someLaterCode(found);
}
~~~
在這里,變量found 做了兩件事:它既是控制標記,也是運算結果。遇到這種情況,我喜歡先把計算found 變量的代碼提煉到一個獨立函數中:
~~~
void checkSecurity(String[] people) {
String found = foundMiscreant(people);
someLaterCode(found);
}
String foundMiscreant(String[] people){
String found = "";
for (int i = 0; i < people.length; i++) {
if (found.equals("")) {
if (people[i].equals ("Don")){
sendAlert();
found = "Don";
}
if (people[i].equals ("John")){
sendAlert();
found = "John";
}
}
}
return found;
}
~~~
然后以return 語句取代控制標記:
~~~
String foundMiscreant(String[] people){
String found = "";
for (int i = 0; i < people.length; i++) {
if (found.equals("")) {
if (people[i].equals ("Don")){
sendAlert();
return "Don";
}
if (people[i].equals ("John")){
sendAlert();
found = "John";
}
}
}
return found;
}
~~~
最后完全去掉控制標記:
~~~
String foundMiscreant(String[] people){
for (int i = 0; i < people.length; i++) {
if (people[i].equals ("Don")){
sendAlert();
return "Don";
}
if (people[i].equals ("John")){
sendAlert();
return "John";
}
}
return "";
}
~~~
即使不需要返回某值,你也可以使用語句來取代控制標記。這時候你只需 要一個空的return 語句就行了。
當然,如果以此辦法去處理帶有副作用(連帶影響)的函數,會有一些問題。所以我需要先以 Separate Query from Modifier 將函數副作用分離出去。稍后你會看到這方面的例子。
- 譯序 by 侯捷
- 譯序 by 熊節
- 序言
- 前言
- 章節一 重構,第一個案例
- 起點
- 重構的第一步
- 分解并重組statement()
- 運用多態(Polymorphism)取代與價格相關的條件邏輯
- 結語
- 章節二 重構原則
- 何謂重構
- 為何重構
- 「重構」助你找到臭蟲(bugs)
- 何時重構
- 怎么對經理說?
- 重構的難題
- 重構與設計
- 重構與性能(Performance)
- 重構起源何處?
- 章節三 代碼的壞味道
- Duplicated Code(重復的代碼)
- Long Method(過長函數)
- Large Class(過大類)
- Long Parameter List(過長參數列)
- Divergent Change(發散式變化)
- Shotgun Surgery(散彈式修改)
- Feature Envy(依戀情結)
- Data Clumps(數據泥團)
- Primitive Obsession(基本型別偏執)
- Switch Statements(switch驚悚現身)
- Parallel Inheritance Hierarchies(平行繼承體系)
- Lazy Class(冗贅類)
- Speculative Generality(夸夸其談未來性)
- Temporary Field(令人迷惑的暫時值域)
- Message Chains(過度耦合的消息鏈)
- Middle Man(中間轉手人)
- Inappropriate Intimacy(狎昵關系)
- Alternative Classes with Different Interfaces(異曲同工的類)
- Incomplete Library Class(不完美的程序庫類)
- Data Class(純稚的數據類)
- Refused Bequest(被拒絕的遺贈)
- Comments(過多的注釋)
- 章節四 構筑測試體系
- 自我測試代碼的價值
- JUnit測試框架
- 添加更多測試
- 章節五 重構名錄
- 重構的記錄格式
- 尋找引用點
- 這些重構準則有多成熟
- 章節六 重新組織你的函數
- Extract Method(提煉函數)
- Inline Method(將函數內聯化)
- Inline Temp(將臨時變量內聯化)
- Replace Temp with Query(以查詢取代臨時變量)
- Introduce Explaining Variable(引入解釋性變量)
- Split Temporary Variable(剖解臨時變量)
- Remove Assignments to Parameters(移除對參數的賦值動作)
- Replace Method with Method Object(以函數對象取代函數)
- Substitute Algorithm(替換你的算法)
- 章節七 在對象之間搬移特性
- Move Method(搬移函數)
- Move Field(搬移值域)
- Extract Class(提煉類)
- Inline Class(將類內聯化)
- Hide Delegate(隱藏「委托關系」)
- Remove Middle Man(移除中間人)
- Introduce Foreign Method(引入外加函數)
- Introduce Local Extension(引入本地擴展)
- 章節八 重新組織數據
- Self Encapsulate Field(自封裝值域)
- Replace Data Value with Object(以對象取代數據值)
- Change Value to Reference(將實值對象改為引用對象)
- Replace Array with Object(以對象取代數組)
- Replace Array with Object(以對象取代數組)
- Duplicate Observed Data(復制「被監視數據」)
- Change Unidirectional Association to Bidirectional(將單向關聯改為雙向)
- Change Bidirectional Association to Unidirectional(將雙向關聯改為單向)
- Replace Magic Number with Symbolic Constant(以符號常量/字面常量取代魔法數)
- Encapsulate Field(封裝值域)
- Encapsulate Collection(封裝群集)
- Replace Record with Data Class(以數據類取代記錄)
- Replace Type Code with Class(以類取代型別碼)
- Replace Type Code with Subclasses(以子類取代型別碼)
- Replace Type Code with State/Strategy(以State/strategy 取代型別碼)
- Replace Subclass with Fields(以值域取代子類)
- 章節九 簡化條件表達式
- Decompose Conditional(分解條件式)
- Consolidate Conditional Expression(合并條件式)
- Consolidate Duplicate Conditional Fragments(合并重復的條件片段)
- Remove Control Flag(移除控制標記)
- Replace Nested Conditional with Guard Clauses(以衛語句取代嵌套條件式)
- Replace Conditional with Polymorphism(以多態取代條件式)
- Introduce Null Object(引入Null 對象)
- Introduce Assertion(引入斷言)
- 章節十一 處理概括關系
- Pull Up Field(值域上移)
- Pull Up Method(函數上移)
- Pull Up Constructor Body(構造函數本體上移)
- Push Down Method(函數下移)
- Push Down Field(值域下移)
- Extract Subclass(提煉子類)
- Extract Superclass(提煉超類)
- Extract Interface(提煉接口)
- Collapse Hierarchy(折疊繼承關系)
- Form Template Method(塑造模板函數)
- Replace Inheritance with Delegation(以委托取代繼承)
- Replace Delegation with Inheritance(以繼承取代委托)
- 章節十二 大型重構
- 這場游戲的本質
- Tease Apart Inheritance(梳理并分解繼承體系)
- Convert Procedural Design to Objects(將過程化設計轉化為對象設計)
- Separate Domain from Presentation(將領域和表述/顯示分離)
- Extract Hierarchy(提煉繼承體系)
- 章節十三 重構,復用與現實
- 現實的檢驗
- 為什么開發者不愿意重構他們的程序?
- 現實的檢驗(再論)
- 重構的資源和參考資料
- 從重構聯想到軟件復用和技術傳播
- 結語
- 參考文獻
- 章節十四 重構工具
- 使用工具進行重構
- 重構工具的技術標準(Technical Criteria )
- 重構工具的實用標準(Practical Criteria )
- 小結
- 章節十五 集成
- 參考書目