如果用很多注释来“装饰”代码是件好事的话,那么在代码中加入大片大片的注释便是锦上添花了。是这样吗?事实上不完全是这样的。过犹不及,好心也会办坏事。
'*************************************************
' Name: CopyString
'
' Purpose: This routine copies a string from the source
' string (source) to the target string (target).
'
' Algorithm: It gets the length of "source" and then copies each
' character, one at a time, into "target". It uses
' the loop index as an array index into both "source"
' and "target" and increments the loop/array index
' after each character is copied.
'
' Inputs: input The string to be copied
'
' Outputs: output The string to receive the copy of "input"
'
' Interface Assumptions: None
'
' Modification History: None
'
' Author: Dwight K. Coder
' Date Created: 10/1/04
' Phone: (555) 222-2255
' SSN: 111-22-3333
' Eye Color: Green
' Maiden Name: None
' Blood Type: AB-
' Mother's Maiden Name: None
' Favorite Car: Pontiac Aztek
' Personalized License Plate: "Tek-ie"
'*************************************************
我常常不看开发者写的注释。似乎他们并不明白,其实他们的代码已经告诉了我它是怎样工作的;我们需要注释告诉我们的是,程序为什么这样工作。代码注释已被广泛地误解和滥用,以致于你都开始怀疑它们原本的价值——注释还有存在的必要吗?你在期望什么呢?要当心!这里有一段完全没有任何注释的代码:
r = n / 2;
while ( abs( r - (n/r) ) > t ) {
r = 0.5 * ( r + (n/r) );
}
System.out.println( "r = " + r );
明白这段代码想要做什么吗?它看起来一清二楚,但到底是干什么用的呢?
让我们加上一行注释:
// 用“牛顿-拉夫逊”近似法求解n的平方根
r = n / 2;
while ( abs( r - (n/r) ) > t ) {
r = 0.5 * ( r + (n/r) );
}
System.out.println( "r = " + r );
这个应该就是我想要的了。不是吗?它介于完全没有任何注释与每隔一行就规规矩矩写上史诗般的注释这两种极端之间,看似一个不错的折中——你满意了吗?
未必!与其添加注释,我更愿意把这段代码重构成这样:
private double SquareRootApproximation(n) {
r = n / 2;
while ( abs( r - (n/r) ) > t ) {
r = 0.5 * ( r + (n/r) );
}
return r;
}
System.out.println( "r = " + SquareRootApproximation(r) );
我一行注释也没有加,但这段神秘的代码现在已经非常容易理解了。