一、编程风格前言:
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"。