CH5, Knowing What to Comment
The purpose of commenting is to help the reader know as much as the writer did.千萬別為了註解而註解, 因為凌亂的畫面, 不會讓人對程式碼更清晰無意義的註解範例
// The class definition for Account
class Account {
public:
// Constructor
Account();
// Set the profit member to a new value
void SetProfit(double profit);
// Return the profit from this Account
double GetProfit();
};
不要註解不好的名稱, 直接修正名稱
// Enforce limits on the Reply as stated in the Request, // such as the number of items returned, or total byte size, etc. void CleanReply(Request request, Reply reply); 直接修改上述function name從CleanReply()改為EnforceLimitsFromRequest()會比註解一堆來得有意義, // Make sure 'reply' meets the count/byte/etc. limits from the 'request' void EnforceLimitsFromRequest(Request request, Reply reply);
Recording Your Thoughts / directory commentary,註解重要的紀錄,比如以下幾個註解
// This heuristic might miss a few words. That's OK; solving this 100% is hard. ... // This class is getting messy. Maybe we should create a 'ResourceNode' subclass to // help organize things. ...
Comment the Flaws in Your Code,程式會不斷的被修改, 不要害怕記錄這些需要改進的地方, 以下是常用的標記
| TODO: | Stuff I haven’t gotten around to yet |
| FIXME: | Known-broken code here |
| HACK: | Admittedly inelegant solution to a problem |
| XXX: | Danger! major problem here |
// TODO: move this into sched_fork() ... // FIXME: do we need to worry about rq being invalidated by the ...
Summary Comments,對一些code給予一些comment, 比如
# Find all the items that customers purchased for themselves.
for customer_id in all_customers:
for sale in all_sales[customer_id].sales:
if sale.recipient == customer_id:
...
def GenerateUserReport():
# Acquire a lock for this user
...
# Read user's info from the database
...
# Write info to a file
...
# Release the lock for this user
...
-
參考資料:
- The Art of Readable Code

沒有留言:
張貼留言