高層註解省略細節,幫助讀者掌握程式碼的整體意圖與結構。

常用於:

  • 方法內部的註解
  • 介面註解

反例:低層、囉嗦的註解#

// If there is a LOADING readRpc using the same session
// as PKHash pointed to by assignPos, and the last PKHash
// in that readRPC is smaller than current assigning
// PKHash, then we put assigning PKHash into that readRPC.
int readActiveRpcId = RPC_ID_NOT_ASSIGNED;
for (int i = 0; i < NUM_READ_RPC; i++) {
    if (session == readRpc[i].session
        && readRpc[i].status == LOADING
        && readRpc[i].maxPos < assignPos
        && readRpc[i].numHashes < MAX_PKHASHES_PERRPC) {
        readActiveRpcId = i;
        break;
    }
}

問題:

  • 部分重複程式碼(「if there is a LOADING readRPC」 = readRpc[i].status == LOADING
  • 沒有說明這段程式碼整體目的是什麼、它如何融入所在的方法

改寫:高層次說明意圖#

// Try to append the current key hash onto an existing
// RPC to the desired server that hasn't been sent yet.

這條註解不寫細節,但讀者光看它就能解釋程式碼大部分行為:

  • 迴圈在掃描所有現存 RPC
  • session 檢查 → 對的伺服器
  • LOADING 檢查 → 還沒送出
  • MAX_PKHASHES_PERRPC → 一次 RPC 能放多少 hash 有上限

只剩 maxPos 檢查需要從程式碼自己看。

高層註解還提供「判斷程式碼是否做對」的基準:把意圖寫清楚,讀者能自行檢視程式碼是否完成所述目標。

寫高層註解比寫低層難#

寫高層註解必須換另一種角度思考程式碼。問自己:

  • 這段程式碼想做什麼
  • 能用最簡單的話總結它的全部嗎?
  • 這段程式碼最重要的事是什麼?

工程師習慣於關注細節(這也是當好工程師的必要條件)。但偉大的設計者能從細節中抽身,從更高層思考系統——這就是抽象的本質。

兩種好的高層註解#

範例:除了「做什麼」,再加「為什麼會走到這」#

if (numProcessedPKHashes < readRpc[i].numHashes) {
    // Some of the key hashes couldn't be looked up in
    // this request (either because they aren't stored
    // on the server, the server crashed, or there
    // wasn't enough space in the response message).
    // Mark the unprocessed hashes so they will get
    // reassigned to new RPCs.
    ...
}
  • 第二句:抽象描述程式碼做什麼
  • 第一句:解釋為什麼會進入這條分支(how we got here

「我們是怎麼走到這的」這類註解極其有用——尤其在記錄方法時,描述「這個方法在什麼情況下被呼叫」往往比描述方法本身更值錢(特別是只在罕見情況才被呼叫的方法)。