注释
优质
小牛编辑
148浏览
2023-12-01
注释
良好的代码自身就是最佳的文档。当你要添加一个注释时,扪心自问,“如何改善代码让它不需要注释?” 改善代码,再写相应文档使之更清楚。
——Steve McConnell
注释超过一个单词时,句首字母应当大写,并在语句停顿或结尾处使用标点符号。句号后添加一个空格。# 差
counter += 1 # Increments counter by one.
好的代码就像是好的笑话 —— 它不需要解释。
——Russ Olsen
注解
如果需要用多行来描述问题,后续行要放在#
后面并缩排两个空格。def bar
# FIXME: This has crashed occasionally since v3.2.1. It may
# be related to the BarBazUtil upgrade.
baz(:quux)
end
当问题是显而易见时,任何文档都是多余的,注解应当放在有问题的那行末尾且不带任何多余说明。这个用法应该算是例外而不是规则。def bar
sleep 100 # OPTIMIZE
end
使用REVIEW
标记需要确认与编码意图是否一致的可疑代码。比如,REVIEW: Are we sure this is how the client does X currently?
。
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.# 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.# 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.# 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