Friday, June 5, 2020

rules of abstraction

在開發軟體的過程中,總是會有幾回,一不小心失手,寫了失敗的 abstraction 。然後,日後再來痛苦地修正。比方說,把這個 abstraction 放棄掉,先變成大量、重複的程式碼,再來觀察規律,重新提鍊。

那有沒有什麼法則,可以用來提醒自己,做簡單的 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