Refactory-Simplify Condition Expression

簡化表達式

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物件

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Decompose Conditional : 將Expression表達式結果明確命名為Method

if (星期一 < Parameter && Parameter < 星期三)  => if ( IsTuesday()) 好處 : 不用在看條件在寫什麼,很直覺的看方法名稱,就知在處理什麼事

Consolidate Conditional Expression : 多if 的 Expression 且回傳相同,將多if 的 Expression 下的Conditional 提取一個Method,回傳值

if (Parameter < 10) return 1
else if (parameter < 20 ) return 1
else if (parameter > 40) return 1  => if (Isthirty()) return 1;

Consolidate Duplicate Conditional Fragments : 多if 的 Expression,有相同method,未return,則將Method放至最後

if (Parameter < 10) {
  a = 1; 
  finishParameter(); 
} else {
  b = 1; 
  finishParameter(); 
}
=>
if (Parameter < 10) 
  a = 1; 
else 
  b = 1; 
  
finishParameter(); 

Remove Control Flag : 於迴圈內,無外部標記影響,則使用break、continue、,若Method 則可用 return

function Test() {
  bool IsStop = false;
  for (int i =0; i < 10 ; i++) {
    if (! IsStop && i > 5)
        IsStop = true;
  }} =>

function Test() {
 for (int i =0; i < 10 ; i++) {
    if (! IsStop && i > 5) break;
 }}

Replace Nested Conditional with Guard Clauses : 多層的If,若某層的if,條件表達式與上下層無影響,則可拉至同一層

string Week = '';
if ( isMonDay)
  Week = MonDay
else {
  if (isTuesDay()) {
      Week = TuesDay;
  else
      Week = OtherDay;
}}  =>

if ( isMonDay())
  Week = MonDay
else if (isTuesDay())
  Week = TuesDay;
else
  Week = OtherDay;

Replace Conditional with Polymorphism : 與oop有關,if 、switch 的條件運算式,依某類別延伸,而執行某類別方法,則可使用Strategy Pattern、Simple Factory

Week week = new Week('星期二');
IDay day = new Day(week); //Simple Factory 
day.getWeek();
}}

Day(Week){
if (week.name === '星期一')
 return new Monday(); //Strategy Pattern Interface方法就不寫了,請去看Strategy Pattern
else if (week.name === '星期二')
 return new Tuesday(); //Strategy Pattern
else if (week.name === '星期三'
 return new Wednesday(); //Strategy Pattern
}

Introduce Null Object 當條件表達式有null時,則多null物件來回傳型別初始值

Day(Week){
if (week.name === '星期一')
 return new Monday(); //Strategy Pattern Interface方法就不寫了,請去看Strategy Pattern
else if (week.name === '星期二')
 return new Tuesday(); //Strategy Pattern
else if (week.name === undefind)
 return new UndefindObject(); //Strategy Pattern
}

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

盡量轉為 c#、Js

ref : https://www.tenlong.com.tw/products/9787115369093