从这一章开始,将讲述变量有关的内容。这里所说的变量是广义的,包括系统自带的类型像整数,数组等,也包括各种自定义的对象。
这一章讲的是一些基本的用法,定义,初始化,生存范围,绑定时间等。
定义要注意的是一定要显式定义,有些语言支持隐式定义,像VB,最好不用,可能出错。
初始化是最容易出错的地方,有一些规则可以尽量减少出错的概率。
- 一、定义的时候初始化。
- 二、第一次使用之前初始化。一二两条和起来最理想的就是在第一次使用之前才定义并初始化。
- 三、对于值不变的变量,用final或者const之类的修饰符。
- 四、对于计数器累加器要格外注意,就是常用的i,j,k,sum等。
- 五、类的成员变量要在构造函数里初始化。
- 六、检查是否需要重新初始化。
- 七、利用编译器检查是否有没初始化的变量。
- 八、检查指针的初始化是否指向正确的内存空间。
- 九、在程序的开始初始化内存,比如全部清零或是全部填充某个值。
- 十、确保每个定义的变量都有用到,没用的就删掉。
变量的生存范围是越小越好,生存时间是越短越好,这样会降低程序的复杂性。要注意的是不要在这个变量已经不存在了还在试图去用它,常见的错误就是指针指向的内存已经释放了,后面还在用。让变量的生存范围小,都集中在那一块,就更容易发现代码中这样的错误。
绑定时间(binding time)就是变量和它的值绑定在一起的时间。常见的有这么几种:
- 一、在写代码的时候,也就是常说的写死了。
- 二、在编译的时候,可能用一些宏定义啊,命名常量啊来实现。
- 三、在装载的时候,从外部存储读进来值。
- 四、在对象实例化的时候,从外部存储读进来值。
- 五、实时的,每次更新都从外部存储读进来值。
从一到五,绑定的时候越来越晚。但这个不一定越晚越好。通常来说,绑定越早,程序越不灵活,但是越简单;绑定越晚,程序越灵活,但是越复杂。这就要有个平衡了,根据需要吧。不过第二种比第一种要好几乎是勿容置疑的。
最后值得一提的是应确保每个变量只用于一个目的。像那种一个temp变量满天飞的做法是相当容易出错的,而且会导致程序的可读性降低。还有一个变量就应该只是它的名字表示的那一种意思,不要还隐藏什么其它的意思。像NumOfPeople,就不要说它非负的时候表示人数,是负数的时候表示缺席的人数,也许你很清楚是这样,但这会给其他人带来很大的困惑。这种做法的起源应该是以前内存很紧张的时候为了省内存,但是事过境迁,现在,99%的情况下,咱不差那几个字节的内存。
Over!附上Checklist:
Checklist: General Issues In Using Variables
Initializing Variables
- Does each routine check input parameters for validity?
- Does the code declare variables close to where they're first used?
- Does the code initialize variables as they're declared, if possible?
- Does the code initialize variables close to where they're first used, if it isn't possible to declare and initialize them at the same time?
- Are counters and accumulators initialized properly and, if necessary, reinitialized each time they are used?
- Are variables reinitialized properly in code that's executed repeatedly?
- Does the code compile with no warnings from the compiler?
- If your language uses implicit declarations, have you compensated for the problems they cause?
Other General Issues in Using Data
- Do all variables have the smallest scope possible?
- Are references to variables as close together as possible-both from each reference to a variable to the next and in total live time?
- Do control structures correspond to the data types?
- Are all the declared variables being used?
- Are all variables bound at appropriate times, that is, striking a conscious balance between the flexibility of late binding and the increased complexity associated with late binding?
- Does each variable have one and only one purpose?
- Is each variable's meaning explicit, with no hidden meanings?