注释
注释
良好的代码自身就是最佳的文档。当你要添加一个注释时,扪心自问,“如何改善代码让它不需要注释?” 改善代码,再写相应文档使之更清楚。
——Steve McConnell
-
编写让人一目了然的代码然后忽略这一节的其它部分。我是认真的!
[link] -
使用英文编写注释。
[link] -
前导
#与注释文本之间应当添加一个空格。
[link] -
注释超过一个单词时,句首字母应当大写,并在语句停顿或结尾处使用标点符号。句号后添加一个空格。
[link] -
避免无谓的注释。
[link]
## 差
counter += 1 # Increments counter by one.
- 及时更新注释。过时的注释比没有注释还要糟糕。
[link]
好的代码就像是好的笑话 —— 它不需要解释。
——Russ Olsen
- 避免替烂代码编写注释。重构它们使其变得一目了然。(要么做,要么不做,不要只是试试看。——Yoda)
[link]
注解
-
注解应该直接写在相关代码之前那行。
[link] -
注解关键字后面,跟着一个冒号及空格,接着是描述问题的文本。
[link] -
如果需要用多行来描述问题,后续行要放在
#后面并缩排两个空格。
[link]
def bar
# FIXME: This has crashed occasionally since v3.2.1. It may
# be related to the BarBazUtil upgrade.
baz(:quux)
end
- 当问题是显而易见时,任何文档都是多余的,注解应当放在有问题的那行末尾且不带任何多余说明。这个用法应该算是例外而不是规则。
[link]
def bar
sleep 100 # OPTIMIZE
end
-
使用
TODO标记应当加入的特征与功能。
[link] -
使用
FIXME标记需要修复的代码。
[link] -
使用
OPTIMIZE标记可能引发性能问题的低效代码。
[link] -
使用
HACK标记代码异味,即那些应当被重构的可疑编码习惯。
[link] -
使用
REVIEW标记需要确认与编码意图是否一致的可疑代码。比如,REVIEW: Are we sure this is how the client does X currently?。
[link] -
适当情况下,可以自行定制其他注解关键字,但别忘记在项目的
README或类似文档中予以说明。
[link]
Magic Comments
- Place magic comments above all code and documentation. Magic comments should only go below shebangs if they are needed in your source file.
[link]
## good
## frozen_string_literal: true
## Some documentation about Person
class Person
end
## bad
## Some documentation about Person
## frozen_string_literal: true
class Person
end
``` ```
## good
#!/usr/bin/env ruby
## frozen_string_literal: true
App.parse(ARGV)
## bad
## frozen_string_literal: true
#!/usr/bin/env ruby
App.parse(ARGV)
- Use one magic comment per line if you need multiple.
[link]
## good
## frozen_string_literal: true
## encoding: ascii-8bit
## bad
## -*- frozen_string_literal: true; encoding: ascii-8bit -*-
- Separate magic comments from code and documentation with a blank line.
[link]
## good
## frozen_string_literal: true
## Some documentation for Person
class Person
# Some code
end
## bad
## frozen_string_literal: true
## Some documentation for Person
class Person
# Some code
end
