iT邦幫忙

2025 iThome 鐵人賽

DAY 13
0
Software Development

沒測試也敢重構?IDE 安全重構 30 日生存指南系列 第 14

Day 14. if 的世界線:如果我能讓它變簡單......

  • 分享至 

  • xImage
  •  

前幾天都在講抽方法、抽參數的東西,今天開始要進到流程控制的部分了,重構最危險的地方也是在這裡。想想過去有多少次在改 if 的時候,因為少加一個驚嘆號 !,而導致整個邏輯反了。透過 Rider 是可以很大機率避免這件事的,今天我們就來看看吧。

1. Invert If

這裡有一個 if 波動拳。大家都知道,程式寫得太巢,會讓可讀性變得很差。我想試著把它改成 Early Return (或稱 Guard Clause) 的寫法。
https://ithelp.ithome.com.tw/upload/images/20250929/20169414CDRIpBmWT0.png

把游標移到 if 上,按下 Show Context Actions,可以看到有個 Invert 'If' 可以用。
https://ithelp.ithome.com.tw/upload/images/20250929/20169414QcphJEbYB9.png

點下去之後,不只是原本的邏輯判斷式、連 return 都幫你安排得妥妥當當,就是這麼簡單。
https://ithelp.ithome.com.tw/upload/images/20250929/20169414lyyeCycMXf.png

2. Convert to Ternary Operator

這裡有一個 if-else,我感覺用三元運算子的寫法會比較簡潔。
https://ithelp.ithome.com.tw/upload/images/20250929/20169414QZeGhdrsUQ.png

一樣把游標移到 if 上,按下 Show Context Actions,有個 Convert to '?:' Operator 可以用。
https://ithelp.ithome.com.tw/upload/images/20250929/20169414k4Knx9ShWV.png

簡簡單單,輕輕鬆鬆。
https://ithelp.ithome.com.tw/upload/images/20250929/20169414n6C3sNG5l5.png

3. Convert to Switch

這邊有好多個 if-else,因為某些會引起宗教戰爭的原因,我想把它改成 switch 的寫法。
https://ithelp.ithome.com.tw/upload/images/20250929/20169414dvBib5GFHn.png

把游標移到 if 上,按下 Show Context Actions,選擇 Convert to 'Switch' Statement
https://ithelp.ithome.com.tw/upload/images/20250929/20169414iYUJycYHbL.png

噹噹!
https://ithelp.ithome.com.tw/upload/images/20250929/20169414DVxhx85tZd.png

4. Inline Control Transfer

繼續上面的例子,若是一個變數有多個賦值,會造成邏輯很難追蹤,也很難做許多種類的重構。把游標移到 return 上,按下 Show Context Actions,選擇 Inline Control Transfer Statement
https://ithelp.ithome.com.tw/upload/images/20250929/20169414aYP10E7E4c.png

可以看到 return 都塞進各個 block 裡面了,瞬間減少多重賦值的問題,這是我最喜歡的重構。
https://ithelp.ithome.com.tw/upload/images/20250929/20169414L4beyboVIO.png

C# 有一個 Switch Expression 的語法,可以讓這個 switch 更簡潔一點。選擇 Convert to 'Switch' Expression
https://ithelp.ithome.com.tw/upload/images/20250929/201694143iFPOOlpfn.png

結果像這樣。
https://ithelp.ithome.com.tw/upload/images/20250929/20169414LrTRTAQA48.png

小結

自從經歷過幾次 if 條件沒改好而導致的 bug 後,碰到 if 的重構時都盡可能避免手改。真的不得已的情況,則千萬、務必、一定要寫測試。明天我們來看更多的 if 重構技。


上一篇
Day 13. Change Signature 之 3:老闆幫我把這邊的參數打包一下
系列文
沒測試也敢重構?IDE 安全重構 30 日生存指南14
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言