2021年3月21日 星期日

[Refactoring] 編寫可讀代碼 筆記

  • 目標: 給未來的自己看懂
  • 方法: 
    • First level: 外在 - naming, alignment
      • Naming
        • 使用精確的詞: e.g. search / load / …
          • get/set 帶有 lightweight 的概念
          • first/last 代表範圍內頭與尾的指標, begin/end 來表示範圍外的指標
        • 避免 tmp, retval 等沒有解釋性的參數名詞
      • Alignment
        • 用 function / macro 等來對齊程式
        • Group 不同目的的 function lists
          • Constructors / deconstructors
          • Getter / setters
          • helper functions
        • 使用段落來註解程式
          • // 1. register database
          • // 2. init
          • // 3. CRUD operations
          • // 4. release resources
      • Comments
        • 移除沒有意義的註解, e.g. variable name has explained
        • 留下設計理念與意圖的註解 (全局觀)
        • 留下 limitation / FIXME / TODO
        • 提供 example (UT)
    • Second level: control flow
      • loops
        • 避免 do-while (except marco using do-while(0))
        • 大多時候避免 goto function
        • 最小化 embedded loops
      • Expressions / variables
        • 利用暫存的解釋變量減少長表達式, 但有時反過來要移除沒必要的中間變量
        • 盡可能縮小 variable scope (避免 global variables)
        • 善用 marcos 縮短表達式長度
    • Third level: 模組化
      • 善用 utility functions 來做到模組化
      • 利用 wrapper function 簡化 interface
      • 各 function 一次只做一件事
      • 熟悉既有 libraries
      • 善用 scripts 處理簡單工作, e.g. awk parse logs
    • Others:
      • Test-driven
      • Sample refactoring flow: from naïve solution to complete solution
    • 延伸閱讀
      • "Code Complete: A Practical Handbook of Software Construction, 2Ed", Steve McConnell
      • "Refactoring: Improving the Design of Existing Code", Martin Fowler
      • "The Practice of Programming", Brian Kernighan and Rob Pike
      • "Clean Code: A Handbook of Agile Software Craftsmanship", RobertC. Martin
      • "Design Patterns: Elements of Reusable Object-Oriented Software", Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides
      • "Programming Pearls, 2Ed", Jon Bentley

2021年3月12日 星期五

[Kid][Health] 禾馨眼科

- 費用: 掛號費(300)+部份負擔(50)+0-7歲自費視力檢查(300)
- 醫師: 王馨儀院長
    - 詳細且認真解說
    - 目前小孩視力會介於 0.6-1.0之間
    - 天生散光
    - 小孩量測時, 因為兒童自己視力的調節、專注力、表達方式都會影響視力報告結果

[Code Review] Check pointer not null

  • C 語言有非常強大的 pointer, 但也因此惡名昭彰
  • 兩個常用的情況是
    • Null pointer check
      •     	if (ptr != NULL) {
                	// do something ...
                } else {
                	// error handling
                }
            
      • 其中就相當多可以討論的地方
        • 要用 if (ptr) 還是 if (ptr != NULL) 還是 if (NULL != ptr)
        • 建議使用 if (ptr) 就好, 幾個理由如下
          • If (ptr ==) 類型的 check, 可能會少寫一個 =, 變成 assignment, 造成難追的 bug
          • NULL 的 implementation 未明確定義, 依不同 compiler 可能實作成 ((char *)0), ((void *) 0), 0, 0L 等
          • 相容於 smart pointer return bool 的 check
          • 降低不必要的 compare
        • Reference: Checking for null pointer in c
    • Memory leak
      • C++ 引入了 unique_ptr, shared_ptr, weak_ptr 等smart pointers
        • Auto release resource at desstructor