一、編程風格前言:
if((country == SING) || (country == BRNI) ||
(country == POL) || (country == ITALY))
{
/*
* if the country is Singapore, Brunei of Poland
* then the current Time is the answer time
* rather than the off hook time.
* Reset answer time and set day of week.
* /
...
}
看起來是非常優秀的代碼。問題:1. 註釋中未提到Italy;2. 註釋中未提到幾個國家的聯繫。
? #define ONE 1
? #define TEN 10
? #define TWENTY 20
問題:宏定義應該表明值在程序中的意義。如下:
#define INPUT_MODE 1
#define INPUT_BUFSIZE 10
#define OUTPUT_BUFSIZE 20
二、命名:
1. 全局用描述性的命名,局部用簡短的命名
int npending = 0; //current length of input queque.
在每個全局變量加上簡短的註釋。全局函數,類,結構體也應該如此。
? for(theElwmwntIndex = 0; theElementIndex < numberofElements;
? theElementIndex++)
? elementArray[theElementIndex] = theElementIndex;
to
for(i = 0; i < nelems; i++)
elem[i] = i;
一直鼓勵較長變量的命名是個誤區,程序本應該清晰、簡潔。
2. 命名的一致性
? class UserQueue{
? int noOfItemsInQ, frontOfTheQueue, queueCapacity;
? public int noOfUsersInQueue() {...}
? }
問題:1. 單詞"queue"出現了Q,Queue和queue; 2. 類的名稱中含有Queue,成員可以不需要"queue"。防止出現:
? queque.queueCapacity
下面是修改後的:
class UserQueue{
int nitems, front, capacity;
public int nuser(){...}
}
如果有以下的語句
queue.capacity++;
n = queue.nuser();
代碼含義十分清晰,但是 "items"和“users"指向同一個事物,因此僅需要其中一個即可。
3. 函數中使用動詞
now = dae.getTime();
putchar('\n');
當函數返回值是布爾時不應該
? if(checkoctal(c)) ...
語句並不能表明返回值是布爾,可以這樣寫
if(isoctal(c)) ...
4. 準確性
宏定義是否爲八進制字符
#define isoctal(c) ((c) >= '0' && (c) <= '7')
而不是
? #define isoctal(c) ((c) >= '0' && (c) <= '8')
下面的函數中,代碼和命名的含義完全相反
? puclic boolean inTable(Object obj)
? int j = this.getIndex(obj);
? return (j == nTable);
? }
程序塊中表達的是"IsnTable",函數名卻是”inTable"。