CH6, Making Comments Precise and Compact
Comments should have a high information-to-space ratio.當你準備寫註解時, 請盡可能的精簡, 因為註解會佔版面, 而且需要時間了解// CategoryType -> (score, weight) typedef hash_map<int, pair<float, float> > ScoreMap; 會比下面例子精簡 // The int is the CategoryType. // The first float in the inner pair is the 'score', // the second is the 'weight'. typedef hash_map<int, pair<float, float> > ScoreMap;
// Return the number of lines in this file. int CountLines(string filename) { ... } 這段註解不精確, 因為一行有很多種定義, 下面例子會相對精準 // Count how many newline bytes ('\n') are in the file. int CountLines(string filename) { ... }
Use Input/Output Examples That Illustrate Corner Cases有時候用範例當註解可以更容易讓人理解,比如
// Rearrange 'v' so that elements < pivot come before those >= pivot; // Then return the largest 'i' for which v[i] < pivot (or -1 if none are < pivot) // Example: Partition([8 5 9 8 2], 8) might result in [5 2 | 8 9 8] and return 1 int Partition(vector<int>* v, int pivot);
"Named Function Parameter” Comments即在function參數上加上註解
Connect(/* timeout_ms = */ 10, /* use_encryption = */ false);
-
參考資料:
- The Art of Readable Code