请避免五种程序注释方式
作者:网络转载 发布时间:[ 2012/11/22 11:12:11 ] 推荐标签:
4、传记型程序员
public class Program
{
static void Main(string[] args)
{
/* I discussed with Jim from Sales over coffee
* at the Starbucks on main street one day and he
* told me that Sales Reps receive commission
* based upon the following structure.
* Friday: 25%
* Wednesday: 15%
* All Other Days: 5%
* Did I mention that I ordered the Caramel Latte with
* a double shot of Espresso?
*/
double price = 5.00;
double commissionRate;
double commission;
if (DateTime.Today.DayOfWeek == DayOfWeek.Friday)
{
commissionRate = .25;
}
else if (DateTime.Today.DayOfWeek == DayOfWeek.Wednesday)
{
commissionRate = .15;
}
else
{
commissionRate = .05;
}
commission = price * commissionRate;
}
}
如果你非得在代码中提到某些必需的东西,也别提到人名。Jim from Sales(译注:销售人员Jim)也许离开这家公司了,那些阅读代码的程序员极可能根本不知道他是谁,更甭提注释里那些毫无干系的事情。
5、“总有”型程序员
public class Program
{
static void Main(string[] args)
{
//TODO: I need to fix this someday – 07/24/1995 Bob
/* I know this error message is hard coded and
* I am relying on a Contains function but
* someday I will make this code print a
* meaningful error message and exit gracefully.
* I just don’t have the time right now.
*/
string message = "An error has occurred";
if(message.Contains("error"))
{
throw new Exception(message);
}
}
}
这类注释在某种程度上说是前面几种类型的大杂烩。TODO注释在项目初始开发阶段用处不小,但是如果几年后出现在产品代码中——那会带来麻烦。如果有什么需要修补的,动手,而不要推迟到以后去做。
如果你不幸是生成这些类型注释的人,或者你想学习注释用法的佳实践,我推荐你阅读Steve McConnell写的Code Complete(《代码大全》)。

sales@spasvo.com