
1

什么是好的程序注释
source link: https://zhiqiang.org/coding/how-to-write-program-comment.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

什么是好的程序注释
以前总是被教育说注释写得越详细越好,我自己写代码的时候也恨不得将每一步都用自然语言给它翻译一遍,如果没写注释就觉得不专业。后来看到健硕写的 notes ,再加上最近做一个东西,也有一些感受。
注释,是为了给自己和别人在下次浏览代码的时候用的,它主要解决三个问题:
- what :下面代码是干嘛用的
- How :下面代码是怎么做的
- Why :为何要写这段代码(为何要这么做)
精确的注释,主要解释清楚第三点:为什么要写这段代码。关于 What 和 How 的注释应该是代码本身。
比如一段代码将一个矩阵排序,一个 code reviewer 看到这段代码时,他需要知道为什么要排序,排序对后续代码有什么影响。而第一点和第二点更多是通过代码本身得到而不需要再写注释去描述了。比如调用了 sort ,即明确说明该段代码是在排序,而调用 quicksort 则是用快速排序法给矩阵排序。
Q. E. D.
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK