java编码4个坏习惯.doc
文本预览下载声明
John OHanley 的这篇文章列举了四个有害的java编码习惯,并提出了改正方案。
这四个习惯普遍存在于java程序员中,并且已经被广泛接受,大家都习以为常,流毒甚远。
1.对局部变量(local variables),字段(fields),参数(method arguments)这三种变量的命名没有区分,造成了代码的阅读困难,增加了代码的维护成本。
作者举了个例子:
public boolean equals (Object arg) {
if (! (arg instanceof Range)) return false;
Range other = (Range) arg;
return start.equals(other.start) end.equals(other.end);
}
在这个方法中,arg直接用argument的缩写,虽然大家一看就知道这是参数了,但这种命名方式却丢失了参数代表的对象本身的含义。大家知道这是参数,却不知道这是什么参数。如果方法的参数多一点,都按照arg1,arg2这样的方式命名,阅读代码的时候很头疼。另外两个字段变量,start和end,突然凭空而出,想一下才知道这应该是字段。当然,这个方法很短,造成的困难还不大,如果这个方法比较长的话,突然看到start和end两个变量,一般会先在前面找一下是不是局部变量,然后才能确定是类的字段变量。
这个问题貌似微不足道,但为什么要让代码阅读者花费额外时间在这些琐碎的问题上呢?如果有个方案能让代码阅读者一目了然的明白变量是那种变量,为什么不采用呢?就如同Steve McConnell在 《代码大全》中说的:让人费神去琢磨神秘杀人凶手这没有问题,但你不需要琢磨程序代码,代码是用来阅读的。
作者提出了解决方案:
方法参数用前缀a开始
类字段变量用前缀f开始
局部变量不用前缀
修正后的代码样式应该是:
public boolean equals (Object aOther) {
if (! (aOther instanceof Range)) return false;
Range other = (Range) aOther;
return fStart.equals(other.fStart) fEnd.equals(other.fEnd);
}
这样的代码看起来一目了然,如果你没有一目了然,说明还是习惯问题,习惯养成了就好了。
不过作者的方案里,给类字段变量前面加 f 前缀,如果用代码生成工具生成get,set方法是会比较麻烦。get,set方法中我们不希望出现个f。不过这个问题可以用修改代码生成工具的方式解决。如果这个习惯普遍被java界接受,这些应该都不成问题了。
作者引用了一句名言:
By relieving the brain of all unnecessary work, a good notation sets it free to concentrate on more advanced problems, and in effect increases the mental power of the race. Before the introduction of the Arabic notation, multiplication was difficult, and the division even of integers called into play the highest mathematical faculties. Probably nothing in the modern world would have more astonished a Greek mathematician than to learn that ... a large proportion of the population of Western Europe could perform the operation of division for the largest numbers. This fact would have seemed to him a sheer impossibility ... Our modern power of easy reckoning with decimal fractions is the almost miraculous result of the gradual discovery of a perfect notation.
-- Alfred North Whitehead, An Introductio
显示全部