<<The Pratice of Programming>>编程风格之命名

一、编程风格前言:

    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"。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值