那有沒有什麼法則,可以用來提醒自己,做簡單的 checklist ,避免自己寫出糟糕的 abstraction 呢? 有的。
rule 1: Wait until the code is repeated three times before you extract it.
rule 2: If you can't think of a good name for your abstraction, it is probably not a thing.
rule 3: Understandable and reusable abstraction is usually less than 10 lines.
法則 1:重複三次才提鍊
法則 2:想出好名字才提鍊
法則 3:一個容易理解、可以重用的抽象,往往少於 10 行。
仔細想想,為什麼寫好 function 是如此的困難呢? 大概是因為我們同時做了三件事吧:
- invent a new purpose
- invent a new implementation
- name it