撰写了文章 发布于 2017-07-04 20:59:59
《代码整洁之道》学习笔记 03-1
注释
注释不能美化糟糕的代码
如果你的代码十分杂乱并且复杂,与其用更多的注释来添加更长的代码阅读时间,不如就重新整洁你的代码,让你的代码方便阅读,根本不需要注释。
用代码来说明
直接创建一个描述和注释所言相同的函数,更加方便代码的阅读。
什么是好的注释
法律信息
代码规范要求,可以尽可能将其指向一份标准许可或外部文档,不需要列出所有条款。(另写一个相关的文件么?)
提供信息注释
比方说明一个抽象方法的返回值,嘛不过最好还是靠代码来说明啦。
对意图的解释
解释对于某种决定后面的意图,比方:
public int compareTo(Object o){
if(o instanceof WikiPagePath){
WikiPagePath p = (WikiPagePath) o;
String compressedName = StringUtil.join(name, "");
String compressedArgumentName = StringUtil.join(p.names, "");
return compressedName.compareTo(compressedArgumentName);
}
return 1;//we are greater because we are the right type.
}阐述
把晦涩难懂的参数或返回值的意义阐述出来(如果参数和返回值是标准库的一部分或是无法修改代码的话,因为尽量建议可以在代码中就显示出来其代表的意义。)
public void testCompareTo() throws Exception{
WikiPagePath a = PathParser.parse("PageA");
WikiPagePath ab = PathParser.parser("PageA.PageB");
...
assertTrue(a.compareTo(a) == 0); //a == a
...
}警示
用于警告其他程序员:“这种傻事我已经干过了,不需要再试了”
TODO注释
嘛,相当于代码的愿望单,有啥想做的一并先列上
放大
String listItemContent = match.group[3].trim();
//the trim is real important.It removes the starting
//spaces that could cause the item to be recognized
//as another list.
new ListItemWidget(this, listItemContent, this.level +1);
return buildList(text.substring(match.end()));
公共API的良好描述
类似Java的javadoc,提升程序编写的效率,当然也要注意之前的几条,防止错误、造成误导或不适用。
