API 是模組間溝通的橋樑,設計良好的 API 能讓程式碼更易使用與維護。
本章介紹如何改善函式的介面設計。
良好的 API 設計應遵循「最小驚訝原則」(Principle of Least Astonishment):
使用者呼叫 API 時,應能直覺地預期其行為,而非需要深入閱讀文件才能避免踩坑。
mindmap
root((重構 APIs))
查詢與修改
Separate Query from Modifier
參數處理
Parameterize Function
Remove Flag Argument
Preserve Whole Object
Replace Parameter with Query
Replace Query with Parameter
物件建構
Remove Setting Method
Replace Constructor with Factory Function
函式與命令
Replace Function with Command
Replace Command with Function