Thursday, October 29, 2009

程式設計注意事項 - 2008.08.17 update

程式設計注意事項 - 2008.08.17 update
by thinker
2 Columns
關鍵字:
coding
幾個注意事項,隨時更新

這些只是建議性原則,將日常遇到的原則問題和解決方法表列。曾在別人的 blog 看到有人提起這篇 memo,表示無法了解規則背後的理由。規則陳述句會盡量精簡,所以並不是每個人都可以看懂。也許像推背圖,事情發生時就會晃然大悟,原來如此 :p 當然,這個 memo 不像推背圖精深、博大。

* 變動和影嚮
o class 或 module 之間,必需依靠 interface 溝通。
o 依靠其它 class 或 module 的結構,容易受其結構變動而影嚮。
o interface 容易適應(adapt) implement 的改變; interface 不變。
o 將 class 或 module 之間的相關性,集中和局限於小範圍,易於變動。
o interface 透過適應程序,能集中和局限因變動而受影嚮的範圍。
o 先確定 class 、 module 或 interface 的關聯,再寫程式。 2007.02.23
o 關聯圖,不離手。 2007.02.23
o 避免、減少 interface 的間接曝露。 2007.02.23
* Closure 代替 function object
o 使用 closure 比 function object 好。
o closure 能減少程式碼。
o closure 將 callback 所需資料,集中在小範圍的 source code 內 (static scope)。
o closure 改善閱讀性。
* 功能切割
o 每個 class 維護單一目標所需的資料。
o function 或 method 提供單一目的。
o 達成目的所需的相關動作,各自分割成 function 、 method 或 class。
+ 資料加入資料庫之後,index 必需更新,則加入動作呼叫 index 更新的 function 或 method,而非全由加入動作獨力完成。
o 若 class 提供大量 callback 的 method, 可考慮以一個或多個 interface 組織 callback methods. 形成 top-down 形式, 較簡單的 topology. (update: 2006.11.28)
* 命名規則
o function 名稱必需有動詞
o function parameter 是名詞
o parameter 出現的順序依照 function 名稱中出現的次序
o 名詞可被省略,但 parameter 出現的次序應該依照原本的次序
o method 的 bond object 是主詞
* 語法使用
o 一行一動作, 一行多動作不利於 debug
o 一行一 function, 呼叫多個 function 不易 debug (錯在哪個 function?)
o 限制括號的層數,不論是大、中、小括號。
+ 太多層的括號,可將之中間的計算過程拆成數行,以利於閱讀。

No comments: