CH1, Code Should Be Easy to Understand
Code should be written to minimize the time it would take for someone else to understand it.
越容易理解的code是越好的, 雖然減少程式碼數量是很好的目標, 但是縮短理解的時間是更為重要的, 甚至於超越效能, 比如bucket = FindBucket(key); if (bucket != NULL) assert(!bucket->IsOccupied()); 會比下面這行更容易被理解 assert((!(bucket = FindBucket(key))) || !bucket->IsOccupied());
CH2, Pack information into your names
提高可讀性可以從"好的名稱", "好的註解", "簡潔的編排方式"著手, 比如, 將資訊放入名稱中void download_page(url); 或 void fetch_page(url); 會比下面這行更容易被理解 void get_page(url);
名稱選擇上也需要注意, 比如open(), begin(), create(), launch()會比start()來的明確, 盡量用明確的命名, 比如tmp_file會比tmp更明確, 比如
var start = (new Date()).getTime(); ... var elasped = (new Date()).getTime(); .. 會比下面這行更容易被明確 var ms_start = (new Date()).getTime(); ... var ms_elasped = (new Date()).getTime(); ..
排除不必要的詞彙, 比如
ToString(); 會比下面這行更簡潔 ConveterToString(); ServerLoop(); 會比下面這行更簡潔 DoServerLoop();
我也習慣在static function,使用"_"開頭, 比如
static void _sleep(); void sleep();
Pack information into your names的幾個重點
• Use specific words—for example, instead of Get, words like Fetch or Download might be better, depending on the context. • Avoid generic names like tmp and retval, unless there’s a specific reason to use them. • Use concrete names that describe things in more detail—the name ServerCanStart() is vague compared to CanListenOnPort(). • Attach important details to variable names—for example, append _ms to a variable whose value is in milliseconds or prepend raw_ to an unprocessed variable that needs escaping. • Use longer names for larger scopes—don’t use cryptic one- or two-letter names for variables that span multiple screens; shorter names are better for variables that span only a few lines. • Use capitalization, underscores, and so on in a meaningful way—for example, you can append “_” to class members to distinguish them from local variables.
-
參考資料:
- The Art of Readable Code
沒有留言:
張貼留言