关于代码的声明虽然看起来是一个很小的问题,但是有很多的学问。Code complete解析的很详细,让人收益匪浅。通常情况下如果代码过长肯定碰到过这样的问题,就是变量的含义或者数值不知道此刻到底保存的是什么值,或者它的初值并不是我们所预料的那样,这个错误将非常难发现。一个好的变量命名可以解决含义的问题(命名问题也非常重要),如何解决另外两个问题了。
那就是用时赋值,声明变量时赋初值。
l Initialize each variable as it’s declared
l Initialize each variable close to where it’s first used
每种语言都有不同的特性,比如VB不支持声明变量时赋初值。只能声明完后在集体赋值,代码如下:
- ' declare all variables
- Dim accountIndex As Integer
- Dim total As Double
- Dim done As Boolean
- ' initialize all variables
- accountIndex = 0
- total = 0
- done = False
- ...
- ' code using accountIndex
- ...
- ' code using total
- ...
- ' code using done
- While Not done
有些
c程序好像也是这样。其实有更好的选择:
- Dim accountIndex As Integer
- accountIndex = 0
- ' code using accountIndex
- ...
- Dim total As Double
- total = 0.0
- ' code using total
- ...
- Dim done As Boolean
- done = False
- ' code using done
- While Not done
可以在使用之前再声明并赋值,这样看程序时不用回过头来再看。如果是c或者ABAP的话,只能在程序开头声明变量,那么就在使用之前再赋初值,虽然ABAP对于每种类型都有初值。但是这样的话可以清楚变量的初值,而不用回过头来再看声明。
l 为什么第二个例子会好于第一个了?比如说done变量的使用,当使用done时,它可能已经被其它函数修改了!尤其在面向过程的语言里。即使它没有被修改,以后的修改程序也可能会。对于这样的程序bug查找也麻烦。
l 第一个声明变量的方法,把所有变量一起在程序开始处声明。给人以全部都是全局变量的感觉,但实际上done只是在末尾才使用。这就和c非常像了,按需声明变量的代码可能更容易看懂。
那理想情况下还是在要使用的时候声明,同时赋初值。一个好的java代码例子如下:
- int accountIndex = 0;
- // code using accountIndex
- ...
- double total = 0.0;
- // code using total
- ...
- boolean done = false;
- // code using done
- while ( ! done ) {
- ...