那就直接介紹第一個精神
S - Single Responsibility
------------------------------------------------------------------------------------------------------------------------
所謂的 Single Responsibility 意思就是每個 class 都只做一件事情
掃地阿姨就只負責掃地,要擦窗戶的話要再寫一個擦窗戶阿姨的 class
這樣做有幾個好處:
1. Testing: 符合 Single Responsibility 的 class 比較好寫 test case
2. 低耦合:因為他的 dependency 會比較少
3. Organization:Smaller, well-organized classes are easier to search than monolithic ones
文中給了一個例子:
假設你有個 Book 的 class,有一些 replace 的 function
之後你有印出來的需求的時候呢
以前的你可能會想要直接寫在 Book 的 class 上面
但這樣就違反 Single Responsibility 了
所以建議這樣做:
O - Open for Extension, Closed for Modification
------------------------------------------------------------------------------------------------------------------------
一言以蔽之就是 classes should be open for extension, but closed for modification. In doing so, we stop ourselves from modifying existing code and causing potential new bugs
屍體寫不少的人應該都有這種經驗
到後期會很排斥改 code,比較喜歡寫新專案
看完這句話我才知道因為我過去都違反這個準則
所以常常把既有的功能改壞,導致每次要改 code 都會有很大的心理負擔
好在作者給出解法
如果你有個 Guitar 的 class
後來嫌吉他素色不夠潮,想要通吉他
千萬不要直接改在吉他的 class 上
再寫一個新的吉他 subclass 去繼承,可以確保你不會搞砸舊的功能
L - Liskov Substitution
------------------------------------------------------------------------------------------------------------------------
這個我大學上「物件導向」的時候好像就有學過
不過那個時候完全沒有 refactor 的概念就是 🤣
如果你的 function 可以接受 Guitar 的話,那我用 SuperCoolGuitarWithFlames 去替換掉也要沒事
I - Interface Segregation
------------------------------------------------------------------------------------------------------------------------
ZooEmployee 這個 Class,請分成 ZooFeeder, ZooCleaner, ZooXXXStaff 等等細小的 class
而不是就設計一個 ZooEmployee 這個職責包山包海的 class,這是慣老闆才做的事XD
D - Dependency Inversion
------------------------------------------------------------------------------------------------------------------------
這是我這次 refactor 最常用的技巧
The principle of Dependency Inversion refers to the decoupling of software modules. This way, instead of high-level modules depending on low-level modules, both will depend on abstractions.
如果你今天要實作一個 Windows98 的 class
請不要直接把 keyboard 和 monitor 直接寫死在裡面