Duplicate
What are your hard rules about commenting?
你评论的硬规则是什么?
A Developer I work with had some things to say about commenting that were interesting to me (see below). What is your personal approach/take on commenting?
我与之合作的开发人员有一些关于我感兴趣的评论的事情(见下文)。您的个人做法/评论意见是什么?
"I don't add comments to code unless its a simple heading or there's a
platform-bug or a necessary work-around that isn't obvious. Code can change and comments may become misleading. Code should be
self-documenting in its use of descriptive names and its logical
organization - and its solutions should be the cleanest/simplest way
to perform a given task. If a programmer can't tell what a program
does by only reading the code, then he's not ready to alter it.
Commenting tends to be a crutch for writing something complex or
non-obvious - my goal is to always write clean and simple code."“我不会在代码中添加注释,除非它是一个简单的标题,或者存在平台错误或必要的解决方案,这是不明显的。代码可能会改变,注释可能会产生误导。代码应该在使用时自我记录描述性名称及其逻辑组织 - 其解决方案应该是执行给定任务的最简洁/最简单的方法。如果程序员不能仅通过读取代码来判断程序的作用,那么他就不准备改变它。往往是写一些复杂或非显而易见的东西 - 我的目标是始终编写干净简单的代码。“
"I think there a few camps when it comes to commenting, the enterprisey-type who think they're writing an API and some grand code-library that will be used for generations to come, the craftsman-like programmer that thinks code says what it does clearer than a comment could, and novices that write verbose/unclear code so as to need to leave notes to themselves as to why they did something."
“我认为在评论方面有一些阵营,那些认为他们正在编写API的企业级人员和一些将用于后代的宏大代码库,工匠般的程序员认为代码说的是什么它比评论更清楚,新手写的是详细/不清楚的代码,因此需要给自己留下笔记,告诉他们为什么要这样做。“
26 个解决方案
#1
There's a tragic flaw with the "self-documenting code" theory. Yes, reading the code will tell you exactly what it is doing. However, the code is incapable of telling you what it's supposed to be doing.
“自我记录代码”理论存在一个悲剧性的缺陷。是的,阅读代码将告诉您它到底在做什么。但是,代码无法告诉您它应该做什么。
I think it's safe to say that all bugs are caused when code is not doing what it's supposed to be doing :). So if we add some key comments to provide maintainers with enough information to know what a piece of code is supposed to be doing, then we have given them the ability to fix a whole lot of bugs.
我认为可以肯定地说,当代码没有做它应该做的事情时,所有错误都会引起:)。因此,如果我们添加一些关键注释来为维护者提供足够的信息来了解一段代码应该做什么,那么我们就已经让他们能够修复大量的错误。
That leaves us with the question of how many comments to put in. If you put in too many comments, things become tedious to maintain and the comments will inevitably be out of date with the code. If you put in too few, then they're not particularly useful.
这就留下了我们要提出多少评论的问题。如果你提出太多评论,那么维护这些事情会变得乏味,而且评论将不可避免地与代码过时。如果你投入太少,那么它们并不是特别有用。
I've found regular comments to be most useful in the following places:
我发现定期评论在以下地方最有用:
1) A brief description at the top of a .h or .cpp file for a class explaining the purpose of the class. This helps give maintainers a quick overview without having to sift through all of the code.
1).h或.cpp文件顶部的简要说明,用于解释课程目的的课程。这有助于维护人员快速浏览,而无需筛选所有代码。
2) A comment block before the implementation of a non-trivial function explaining the purpose of it and detailing its expected inputs, potential outputs, and any oddities to expect when calling the function. This saves future maintainers from having to decipher entire functions to figure these things out.
2)在执行非平凡函数之前的注释块,解释其目的并详细说明其预期输入,潜在输出以及调用函数时预期的任何奇怪之处。这使得未来的维护者不必破译整个功能来解决这些问题。
Other than that, I tend to comment anything that might appear confusing or odd to someone. For example: "This array is 1 based instead of 0 based because of blah blah".
除此之外,我倾向于评论任何可能对某人感到困惑或奇怪的事情。例如:“由于等等,这个数组是基于1而不是基于0”。
Well written, well placed comments are invaluable. Bad comments are often worse than no comments. To me, lack of any comments at all indicates laziness and/or arrogance on the part of the author of the code. No matter how obvious it is to you what the code is doing or how fantastic your code is, it's a challenging task to come into a body of code cold and figure out what the heck is going on. Well done comments can make a world of difference getting someone up to speed on existing code.
写得好,评价良好的评论非常宝贵。糟糕的评论往往比没有评论更糟糕。对我来说,没有任何评论表明代码作者的懒惰和/或傲慢。无论你对代码的作用有多么明显,或者你的代码有多么美妙,进入一个代码体并且弄清楚它到底发生了什么是一项具有挑战性的任务。做得好的评论可以让人们加快现有代码的速度。
#2
I've always liked Refactoring's take on commenting:
我一直很喜欢Refactoring的评论:
The reason we mention comments here is that comments often are used as a deodorant. It's surprising how often you look at thickly commented code and notice that the comments are there because the code is bad.
我们在这里提到评论的原因是评论经常被用作除臭剂。令人惊讶的是,您经常查看厚度注释的代码,并注意到注释是存在的,因为代码很糟糕。
Comments lead us to bad code that has all the rotten whiffs we've discussed in the rest of this chapter. Our first action is to remove the bad smells by refactoring. When we're finished, we often find that the comments are superfluous.
评论引导我们看到错误的代码,这些代码包含了我们在本章其余部分讨论过的所有腐烂的气味。我们的第一个行动是通过重构消除难闻的气味。当我们完成时,我们经常发现评论是多余的。
As controversial as that is, it's rings true for the code I've read. To be fair, Fowler isn't saying to never comment, but to think about the state of your code before you do.
尽管有争议,但对于我读过的代码来说,这是真的。公平地说,福勒并不是说永远不会发表评论,而是在你做之前考虑代码的状态。
#3
You need documentation (in some form; not always comments) for a local understanding of the code. Code by itself tells you what it does, if you read all of it and can keep it all in mind. (More on this below.) Comments are best for informal or semiformal documentation.
您需要文档(以某种形式;并不总是注释)以便本地理解代码。代码本身会告诉您它的作用,如果您阅读了所有内容并且可以牢记这一点。 (更多内容见下文。)评论最适合非正式或半正式文档。
Many people say comments are a code smell, replaceable by refactoring, better naming, and tests. While this is true of bad comments (which are legion), it's easy to jump to concluding it's always so, and hallelujah, no more comments. This puts all the burden of local documentation -- too much of it, I think -- on naming and tests.
许多人说评论是代码气味,可以通过重构,更好的命名和测试来替换。虽然糟糕的评论(即军团)也是如此,但很容易跳到总结如此,哈利路亚,没有更多的评论。这使得本地文档的所有负担 - 我认为太多 - 在命名和测试上。
Document the contract of each function and, for each type of object, what it represents and any constraints on a valid representation (technically, the abstraction function and representation invariant). Use executable, testable documentation where practical (doctests, unit tests, assertions), but also write short comments giving the gist where helpful. (Where tests take the form of examples, they're incomplete; where they're complete, precise contracts, they can be as much work to grok as the code itself.) Write top-level comments for each module and each project; these can explain conventions that keep all your other comments (and code) short. (This supports naming-as-documentation: with conventions established, and a place we can expect to find subtleties noted, we can be confident more often that the names tell all we need to know.) Longer, stylized, irritatingly redundant Javadocs have their uses, but helped generate the backlash.
记录每个函数的契约,并为每种类型的对象记录它代表的内容以及对有效表示的任何约束(技术上,抽象函数和表示不变)。在可行的情况下使用可执行的,可测试的文档(doctests,单元测试,断言),但也要写一些简短的评论,给出有用的要点。 (如果测试采用示例的形式,它们是不完整的;如果它们是完整的,精确的合同,它们可以像代码本身那样进行工作。)为每个模块和每个项目编写*注释;这些可以解释保持所有其他注释(和代码)简短的约定。 (这支持命名为文档:建立了约定,并且我们可以期待找到微妙的地方,我们可以更频繁地确信这些名称告诉我们需要知道的所有内容。)更长,风格化,烦躁多余的Javadocs有他们的使用,但帮助产生反弹。
(For instance, this:
(例如,这个:
Perform an n-fold frobulation.
@param n the number of times to frobulate
@param x the x-coordinate of the center of frobulation
@param y the y-coordinate of the center of frobulation
@param z the z-coordinate of the center of frobulation执行n次fr选。 @param n frobulate @param的次数x frobulation中心的x坐标@param y frobulation中心的y坐标@param z frobulation中心的z坐标
could be like "Frobulate n times around the center (x,y,z)." Comments don't have to be a chore to read and write.)
可能就像“围绕中心(x,y,z)发生n次。”评论不一定是读写的苦差事。)
I don't always do as I say here; it depends on how much I value the code and who I expect to read it. But learning how to write this way made me a better programmer even when cutting corners.
我不像我在这里说的那样做;这取决于我对代码的重视程度以及我希望阅读的代码。但是学习如何用这种方式写作让我成为一个更好的程序员,即使是在偷工减料。
Back on the claim that we document for the sake of local understanding: what does this function do?
回到我们为了本地理解而记录的声明:这个函数有什么作用?
def is_even(n): return is_odd(n-1)
Tests if an integer is even? If is_odd()
tests if an integer is odd, then yes, that works. Suppose we had this:
测试整数是否均匀?如果is_odd()测试一个整数是奇数,那么是的,这是有效的。假设我们有这个:
def is_odd(n): return is_even(n-1)
The same reasoning says this is_odd()
tests if an integer is odd. Put them together, of course, and neither works, even though each works if the other does. Change it a bit and we'd have code that does work, but only for natural numbers, while still locally looking like it works for integers. In microcosm that's what understanding a codebase is like: tracing dependencies around in circles to try to reverse-engineer assumptions the author could have explained in a line or two if they'd bothered. I hate the expense of spirit thoughtless coders have put me to this way over the past couple of decades: oh, this method looks like it has the side effect of farbuttling the warpcore... always? Well, if odd crobuncles desaturate, at least; do they? Better check all the crobuncle-handling code... which will pose its own challenges to understanding. Good documentation cuts this O(n) pointer-chasing down to O(1): e.g. knowing a function's contract and the contracts of the things it explicitly uses, the function's code should make sense with no further knowledge of the system. (Here, contracts saying is_even()
and is_odd()
work on natural numbers would tell us that both functions need to test for n==0
.)
同样的推理说这个is_odd()测试一个整数是奇数。当然,将它们组合在一起并且都不起作用,即使每个都有效也是如此。稍微更改一下,我们的代码可以正常工作,但仅适用于自然数字,而本地看起来仍适用于整数。在微观世界中,这就是理解代码库的方式:跟踪圈内的依赖关系,试图对假设进行反向工程,如果他们感到烦恼,作者可能会在一两行中解释。在过去的几十年里,我讨厌精神上没有精神的程序员让我这样做的费用:噢,这种方法看起来好像它具有挫败战争核心的副作用......总是?好吧,如果奇怪的crobuncles去饱和,至少;他们呢?更好地检查所有crobuncle处理代码......这将对理解提出自己的挑战。好的文档会将这个O(n)指针切换为O(1):例如:知道一个函数的契约和它明确使用的东西的契约,函数的代码应该没有进一步的系统知识。 (这里,关于自然数的is_even()和is_odd()的合同会告诉我们两个函数都需要测试n == 0。)
#4
My only real rule is that comments should explain why code is there, not what it is doing or how it is doing it. Those things can change, and if they do the comments have to be maintained. The purpose the code exists in the first place shouldn't change.
我唯一真正的规则是评论应该解释为什么代码存在,而不是它正在做什么或它是如何做的。这些事情可以改变,如果他们这样做,则必须保持评论。代码首先存在的目的不应该改变。
#5
the purpose of comments is to explain the context - the reason for the code; this, the programmer cannot know from mere code inspection. For example:
评论的目的是解释背景 - 代码的原因;这,程序员无法从单纯的代码检查中知道。例如:
strangeSingleton.MoveLeft(1.06);
badlyNamedGroup.Ignite();
who knows what the heck this is for? but with a simple comment, all is revealed:
谁知道这是为了什么?但只有简单的评论,所有内容都显示出来:
//when under attack, sidestep and retaliate with rocket bundles
strangeSingleton.MoveLeft(1.06);
badlyNamedGroup.Ignite();
seriously, comments are for the why, not the how, unless the how is unintuitive.
严肃地说,评论是为什么,而不是如何,除非如何不直观。
#6
While I agree that code should be self-readable, I still see a lot of value in adding extensive comment blocks for explaining design decisions. For example "I did xyz instead of the common practice of abc because of this caveot ..." with a URL to a bug report or something.
虽然我同意代码应该是自我可读的,但我仍然认为在添加广泛的注释块以解释设计决策方面有很多价值。例如“我做了xyz而不是abc的常见做法,因为这个洞穴......”带有错误报告的URL或其他东西。
I try to look at it as: If I'm dead and gone and someone straight out of college has to fix a bug here, what are they going to need to know?
我试着将其视为:如果我已经死了并且已经离开并且大学毕业的人必须在这里修复一个错误,他们需要知道什么?
#7
In general I see comments used to explain poorly written code. Most code can be written in a way that would make comments redundant. Having said that I find myself leaving comments in code where the semantics aren't intuitive, such as calling into an API that has strange or unexpected behavior etc...
一般来说,我看到用于解释写得不好的代码的注释。大多数代码都可以以使注释冗余的方式编写。话虽如此,我发现自己在代码中留下了注释,其中语义不直观,例如调用具有奇怪或意外行为等的API ......
#8
I also generally subscribe to the self-documenting code idea, so I think your developer friend gives good advice, and I won't repeat that, but there are definitely many situations where comments are necessary.
我通常也会订阅自我记录代码的想法,所以我认为你的开发者朋友提供了很好的建议,我不会重复,但肯定有很多情况需要注释。
A lot of times I think it boils down to how close the implementation is to the types of ordinary or easy abstractions that code-readers in the future are going to be comfortable with or more generally to what degree the code tells the entire story. This will result in more or fewer comments depending on the type of programming language and project.
很多时候,我认为它归结为实现与普通或简单抽象的类型有多接近,未来的代码阅读器将会感到舒适,或者更普遍的是代码告诉整个故事的程度。这将导致更多或更少的注释,具体取决于编程语言和项目的类型。
So, for example if you were using some kind of C-style pointer arithmetic in an unsafe C# code block, you shouldn't expect C# programmers to easily switch from C# code reading (which is probably typically more declarative or at least less about lower-level pointer manipulation) to be able to understand what your unsafe code is doing.
因此,例如,如果您在不安全的C#代码块中使用某种C风格的指针算法,您不应期望C#程序员能够轻松地从C#代码读取切换(这可能通常更具说明性或至少更低一些 - 级别指针操作),以便能够理解您的不安全代码正在做什么。
Another example is when you need to do some work deriving or researching an algorithm or equation or something that is not going to end up in your code but will be necessary to understand if anyone needs to modify your code significantly. You should document this somewhere and having at least a reference directly in the relevant code section will help a lot.
另一个例子是当你需要做一些工作来推导或研究一个算法或方程式或者某些不会在你的代码中结束的东西,但是有必要了解是否有人需要显着修改你的代码。你应该在某个地方记录这一点,并且在相关的代码部分中至少直接引用将有很大帮助。
#9
I don't think it matters how many or how few comments your code contains. If your code contains comments, they have to maintained, just like the rest of your code.
我认为您的代码包含多少或几个评论并不重要。如果您的代码包含注释,则必须维护它们,就像代码的其余部分一样。
EDIT: That sounded a bit pompous, but I think that too many people forget that even the names of the variables, or the structures we use in the code, are all simply "tags" - they only have meaning to us, because our brains see a string of characters such as customerNumber
and understand that it is a customer number. And while it's true that comments lack any "enforcement" by the compiler, they aren't so far removed. They are meant to convey meaning to another person, a human programmer that is reading the text of the program.
编辑:这听起来有点浮夸,但我认为有太多人忘记即使是变量的名称,或者我们在代码中使用的结构,都只是“标签” - 它们只对我们有意义,因为我们的大脑查看一串字符,例如customerNumber,并了解它是一个客户编号。尽管评论缺乏编译器的任何“强制执行”,但它们并没有被删除。它们旨在向另一个人传达意义,一个正在阅读该程序文本的人类程序员。
#10
If the code is not clear without comments, first make the code a clearer statement of intent, then only add comments as needed.
如果没有注释的代码不清楚,首先使代码更清晰的意图声明,然后只根据需要添加注释。
Comments have their place, but primarily for cases where the code is unavoidably subtle or complex (inherent complexity is due to the nature of the problem being solved, not due to laziness or muddled thinking on the part of the programmer).
评论有其自己的位置,但主要用于代码不可避免地微妙或复杂的情况(固有的复杂性是由于问题的性质得到解决,而不是由于程序员的懒惰或混乱的思维)。
Requiring comments and "measuring productivity" in lines-of-code can lead to junk such as:
在代码行中要求注释和“衡量生产力”可能导致垃圾,例如:
/*****
*
* Increase the value of variable i,
* but only up to the value of variable j.
*
*****/
if (i < j) {
++i;
} else {
i = j;
}
rather than the succinct (and clear to the appropriately-skilled programmer):
而不是简洁(并且适当熟练的程序员清楚):
i = Math.min(j, i + 1);
YMMV
#11
The vast majority of my commnets are at the class-level and method-level, and I like to describe the higher-level view instead of just args/return value. I'm especially careful to describe any "non-linearities" in the function (limits, corner cases, etc) that could trip up the unwary.
我的绝大多数通信都是在类级别和方法级别,我喜欢描述更高级别的视图而不仅仅是args / return值。我特别小心地描述了函数中的任何“非线性”(限制,极端情况等),这些都可能会让人不知所措。
Typically I don't comment inside a method, except to mark "FIXME" items, or very occasionally some sort of "here be monsters" gotcha that I just can't seem to clean up, but I work very hard to avoid those. As Fowler says in Refactoring, comments tend to indicate smally code.
通常情况下我不会在方法内部发表评论,除了标记“FIXME”项目,或者偶尔会出现某些“这里是怪物”,我似乎无法清理,但我努力避免这些。正如Fowler在Refactoring中所说,评论往往表明代码很少。
#12
Comments are part of code, just like functions, variables and everything else - and if changing the related functionality the comment must also be updated (just like function calls need changing if function arguments change).
注释是代码的一部分,就像函数,变量和其他所有东西一样 - 如果更改相关功能,注释也必须更新(就像函数调用需要更改,如果函数参数更改)。
In general, when programming you should do things once in one place only.
一般来说,编程时你应该只在一个地方做一次。
Therefore, if what code does is explained by clear naming, no comment is needed - and this is of course always the goal - it's the cleanest and simplest way.
因此,如果通过明确命名解释了什么代码,则不需要评论 - 这当然也是目标 - 这是最干净,最简单的方法。
However, if further explanation is needed, I will add a comment, prefixed with INFO, NOTE, and similar...
An INFO: comment is for general information if someone is unfamiliar with this area.
A NOTE: comment is to alert of a potential oddity, such as a strange business rule / implementation.
If I specifically don't want people touching code, I might add a WARNING: or similar prefix.
但是,如果需要进一步说明,我将添加一个注释,前缀为INFO,NOTE和类似的...一个INFO:注释用于一般信息,如果有人不熟悉这个区域。注意:注释是警告潜在的奇怪,例如奇怪的业务规则/实现。如果我特别不希望人们接触代码,我可能会添加一个警告:或类似的前缀。
What I don't use, and am specifically opposed to, are changelog-style comments - whether inline or at the head of the file - these comments belong in the version control software, not the sourcecode!
我不使用,并且特别反对的是更改日志样式的注释 - 无论是内联还是文件的头部 - 这些注释属于版本控制软件,而不是源代码!
#13
I prefer to use "Hansel and Gretel" type comments; little notes in the code as to why I'm doing it this way, or why some other way isn't appropriate. The next person to visit this code will probably need this info, and more often than not, that person will be me.
我更喜欢使用“Hansel and Gretel”类型的评论;代码中的小注释,为什么我这样做,或者为什么其他方式不合适。下一个访问此代码的人可能需要这些信息,而且通常情况下,那个人将是我。
#14
As a contractor I know that some people maintaining my code will be unfamiliar with the advanced features of ADO.Net I am using. Where appropriate, I add a brief comment about the intent of my code and a URL to an MSDN page that explains in more detail.
作为承包商,我知道有些人维护我的代码将不熟悉我正在使用的ADO.Net的高级功能。在适当的情况下,我添加了一个关于我的代码意图的简短评论和一个更详细解释的MSDN页面的URL。
I remember learning C# and reading other people's code I was often frustrated by questions like, "which of the 9 meanings of the colon character does this one mean?" If you don't know the name of the feature, how do you look it up?! (Side note: This would be a good IDE feature: I select an operator or other token in the code, right click then shows me it's language part and feature name. C# needs this, VB less so.)
我记得学习C#并阅读其他人的代码我常常对这样的问题感到沮丧,比如“结肠字符的9个含义中哪一个意味着什么?”如果您不知道该功能的名称,您如何查找?! (旁注:这将是一个很好的IDE功能:我在代码中选择一个运算符或其他标记,右键单击然后显示它的语言部分和功能名称.C#需要这个,VB不那么。)
As for the "I don't comment my code because it is so clear and clean" crowd, I find sometimes they overestimate how clear their very clever code is. The thought that a complex algorithm is self-explanatory to someone other than the author is wishful thinking.
至于“我不评论我的代码,因为它是如此清晰和干净”的人群,我发现有时他们高估了他们非常聪明的代码是多么清晰。认为复杂算法对作者以外的其他人不言自明的想法是一厢情愿的想法。
And I like @17 of 26's comment (empahsis added):
我喜欢26的评论中的第17条(empahsis补充):
... reading the code will tell you exactly what it is doing. However, the code is incapable of telling you what it's supposed to be doing.
...阅读代码将告诉你它到底在做什么。但是,代码无法告诉您它应该做什么。
#15
I very very rarely comment. MY theory is if you have to comment it's because you're not doing things the best way possible. Like a "work around" is the only thing I would comment. Because they often don't make sense but there is a reason you are doing it so you need to explain.
我很少发表评论。我的理论是,如果你必须评论它,因为你没有尽可能最好地做事。就像“解决方法”一样,我唯一会评论。因为它们通常没有意义,但是你有理由这样做,所以你需要解释。
Comments are a symptom of sub-par code IMO. I'm a firm believer in self documenting code. Most of my work can be easily translated, even by a layman, because of descriptive variable names, simple form, and accurate and many methods (IOW not having methods that do 5 different things).
评论是IMO低于标准代码的症状。我坚信自我记录代码。由于描述性变量名称,简单形式,准确和许多方法(IOW没有方法可以做5种不同的事情),我的大部分工作都可以轻松翻译,即使是外行也是如此。
#16
Comments are part of a programmers toolbox and can be used and abused alike. It's not up to you, that other programmer, or anyone really to tell you that one tool is bad overall. There are places and times for everything, including comments.
注释是程序员工具箱的一部分,可以使用和滥用。这不是由你,其他程序员或任何人真正告诉你一个工具总体上是坏的。一切都有地方和时间,包括评论。
I agree with most of what's been said here though, that code should be written so clear that it is self-descriptive and thus comments aren't needed, but sometimes that conflicts with the best/optimal implementation, although that could probably be solved with an appropriately named method.
我同意这里所说的大部分内容,但是代码应该写得如此清晰,以至于它是自我描述性的,因此不需要注释,但有时会与最佳/最佳实现冲突,尽管这可能通过一个适当命名的方法。
#17
I agree with the self-documenting code theory, if I can't tell what a peice of code is doing simply by reading it then it probably needs refactoring, however there are some exceptions to this, I'll add a comment if:
我同意自我记录代码理论,如果我只是通过阅读它无法分辨代码的作用,那么它可能需要重构,但是有一些例外,我会在以下情况下添加注释:
- I'm doing something that you don't normally see
- There are major side effects or implementation details that aren't obvious, or won't be next year
- I need to remember to implement something although I prefer an exception in these cases.
- If I'm forced to go do something else and I'm having good ideas, or a difficult time with the code, then I'll add sufficient comments to tmporarily preserve my mental state
我正在做一些你通常看不到的事情
有明显的副作用或实施细节,或明年不会
我需要记住实现一些东西,尽管在这些情况下我更喜欢异常。
如果我*去做其他事情并且我有很好的想法,或者代码很难,那么我会添加足够的评论来暂时保留我的精神状态
#18
Most of the time I find that the best comment is the function or method name I am currently coding in. All other comments (except for the reasons your friend mentioned - I agree with them) feel superfluous.
大多数时候我发现最好的评论是我目前编写的函数或方法名称。所有其他评论(除了你朋友提到的原因 - 我同意他们的观点)感觉多余。
So in this instance commenting feels like overkill:
所以在这种情况下,评论感觉有点矫枉过正:
/*
* this function adds two integers
*/
int add(int x, int y)
{
// add x to y and return it
return x + y;
}
because the code is self-describing. There is no need to comment this kind of thing as the name of the function clearly indicates what it does and the return statement is pretty clear as well. You would be surprised how clear your code becomes when you break it down into tiny functions like this.
因为代码是自我描述的。没有必要评论这种事情,因为函数的名称清楚地表明它的作用,并且return语句也非常清楚。当你将代码细分为像这样的小函数时,你会感到惊讶。
#19
When programming in C, I'll use multi-line comments in header files to describe the API, eg parameters and return value of functions, configuration macros etc...
在C语言编程时,我将在头文件中使用多行注释来描述API,例如函数的参数和返回值,配置宏等......
In source files, I'll stick to single-line comments which explain the purpose of non-self-evident pieces of code or to sub-section a function which can't be refactored to smaller ones in a sane way. Here's an example of my style of commenting in source files.
在源文件中,我将坚持单行注释,这些注释解释了非自明的代码片段的目的,或者将一个不能以理智的方式重构为较小的函数的子函数。这是我在源文件中评论风格的一个例子。
If you ever need more than a few lines of comments to explain what a given piece of code does, you should seriously consider if what you're doing can't be done in a better way...
如果您需要多行注释来解释给定代码片段的作用,那么您应该认真考虑一下您所做的事情是否无法以更好的方式完成...
#20
I write comments that describe the purpose of a function or method and the results it returns in adequate detail. I don't write many inline code comments because I believe my function and variable naming to be adequate to understand what is going on.
我编写的注释描述了函数或方法的用途以及它返回的结果。我不会写很多内联代码注释,因为我相信我的函数和变量命名足以理解正在发生的事情。
I develop on a lot of legacy PHP systems that are absolutely terribly written. I wish the original developer would have left some type of comments in the code to describe what was going on in those systems. If you're going to write indecipherable or bad code that someone else will read eventually, you should comment it.
我在很多遗留的PHP系统上开发,这些系统写得非常糟糕。我希望原始开发人员在代码中留下某种类型的注释来描述这些系统中发生的事情。如果您要编写其他人最终会阅读的难以理解或错误的代码,您应该对其进行评论。
Also, if I am doing something a particular way that doesn't look right at first glance, but I know it is because the code in question is a workaround for a platform or something like that, then I'll comment with a WARNING comment.
另外,如果我正在做一些看起来不太正确的特定方式,但我知道这是因为有问题的代码是平台的解决方法或类似的东西,那么我将使用警告评论进行评论。
#21
Sometimes code does exactly what it needs to do, but is kind of complicated and wouldn't be immediately obvious the first time someone else looked at it. In this case, I'll add a short inline comment describing what the code is intended to do.
有时代码确实完成了它需要做的事情,但有点复杂,并且在第一次有人看到它时不会立即明显。在这种情况下,我将添加一个简短的内联注释,描述代码的目的。
I also try to give methods and classes documentation headers, which is good for intellisense and auto-generated documentation. I actually have a bad habit of leaving 90% of my methods and classes undocumented. You don't have time to document things when you're in the middle of coding and everything is changing constantly. Then when you're done you don't feel like going back and finding all the new stuff and documenting it. It's probably good to go back every month or so and just write a bunch of documentation.
我还尝试给出方法和类文档头文件,这对于intellisense和自动生成的文档很有用。我实际上有一个坏习惯,就是让90%的方法和课程都没有记录。当您处于编码过程中并且一切都在不断变化时,您没有时间记录事物。然后,当你完成后,你不想回去找到所有新东西并记录下来。每个月左右回来并写一堆文档可能会很好。
#22
Here's my view (based on several years of doctoral research):
这是我的观点(基于几年的博士研究):
There's a huge difference between commenting functions (sort of a black box use, like JavaDocs), and commenting actual code for someone who will read the code ("internal commenting").
注释函数(类似黑盒使用,如JavaDocs)和为读取代码的人(“内部注释”)评论实际代码之间存在巨大差异。
Most "well written" code shouldn't require much "internal commenting" because if it performs a lot then it should be broken into enough function calls. The functionality for each of these calls is then captured in the function name and in the function comments.
大多数“写得好”的代码不应该需要太多的“内部评论”,因为如果它执行了很多,那么它应该分解成足够的函数调用。然后,在函数名称和函数注释中捕获每个调用的功能。
Now, function comments are indeed the problem, and in some ways your friend is right, that for most code there is no economical incentive for complete specifications the way that popular APIs are documented. The important thing here is to identify what are the "directives": directives are those information pieces that directly affect clients, and require some direct action (and are often unexpected). For example, X must be invoked before Y, don't call this from outside a UI thread, be aware that this has a certain side effect, etc. These are the things that are really important to capture.
现在,函数注释确实是问题所在,并且在某些方面你的朋友是对的,对于大多数代码来说,对于完整的规范没有经济上的激励,就像流行的API被记录一样。这里重要的是确定什么是“指令”:指令是那些直接影响客户的信息片段,需要一些直接的操作(并且通常是意外的)。例如,X必须在Y之前调用,不要从UI线程外部调用它,要知道这有一定的副作用,等等。这些是捕获非常重要的事情。
Since most people never read full function documentations, and skim what they do read, you can actually increase the chances of awareness by capturing only the directives rather than the whole description.
由于大多数人从不阅读完整的功能文档,并浏览他们所阅读的内容,因此实际上可以通过仅捕获指令而不是整个描述来增加意识的机会。
#23
I comment as much as needed - then, as much as I will need it a year later.
我尽可能多地评论 - 然后,就像我一年后需要的那样。
#24
We add comments which provide the API reference documentation for all public classes / methods / properties / etc... This is well worth the effort because XML Documentation in C# has the nice effect of providing IntelliSense to users of these public APIs. .NET 4.0's code contracts will enable us to improve further on this practice.
我们添加注释,为所有公共类/方法/属性/等提供API参考文档......这非常值得,因为C#中的XML文档具有为这些公共API的用户提供IntelliSense的良好效果。 .NET 4.0的代码合同将使我们能够进一步改进这种做法。
As a general rule, we do not document internal implementations as we write code unless we are doing something non-obvious. The theory is that while we are writing new implementations, things are changing and comments are more likely than not to be wrong when the dust settles.
作为一般规则,我们不会在编写代码时记录内部实现,除非我们做了一些不明显的事情。理论是,当我们正在编写新的实现时,事情正在发生变化,当尘埃落定时,评论更有可能不会出错。
When we go back in to work on an existing piece of code, we add comments when we realize that it's taking some thought to figure out what in the heck is going on. This way, we wind up with comments where they are more likely to be correct (because the code is more stable) and where they are more likely to be useful (if I'm coming back to a piece of code today, it seems more likely that I might come back to it again tomorrow).
当我们回到现有的代码片段时,我们会在我们意识到它正在考虑找出正在发生的事情时添加注释。通过这种方式,我们最终得出的评论更可能是正确的(因为代码更稳定),并且它们更有可能是有用的(如果我今天回到一段代码,它似乎更多可能我明天可能会再次回到它。
#25
My approach:
Comments bridge the gap between context / real world and code. Therefore, each and every single line is commented, in correct English language.
评论弥合了上下文/现实世界和代码之间的差距。因此,每一行都以正确的英语进行评论。
I DO reject code that doesn't observe this rule in the strictest possible sense.
我拒绝在最严格意义上不遵守此规则的代码。
Usage of well formatted XML - comments is self-evident.
使用格式良好的XML - 注释是不言而喻的。
Sloppy commenting means sloppy code!
邋comment的评论意味着草率的代码!
#26
Here's how I wrote code:
这是我编写代码的方式:
if (hotel.isFull()) {
print("We're fully booked");
} else {
Guest guest = promptGuest();
hotel.checkIn(guest);
}
here's a few comments that I might write for that code:
这里有一些我可能会为该代码编写的评论:
// if hotel is full, refuse checkin, otherwise
// prompt the user for the guest info, and check in the guest.
If your code reads like a prose, there is no sense in writing comments that simply repeats what the code reads since the mental processing needed for reading the code and the comments would be almost equal; and if you read the comments first, you will still need to read the code as well.
如果你的代码看起来像散文,那么编写注释只是重复代码读取的内容是没有意义的,因为阅读代码所需的心理处理和注释几乎相同;如果您先阅读注释,您仍需要阅读代码。
On the other hand, there are situations where it is impossible or extremely difficult to make the code looks like a prose; that's where comment could patch in.
另一方面,有些情况下,使代码看起来像散文是不可能或极难的;那是评论可以补丁的地方。
#1
There's a tragic flaw with the "self-documenting code" theory. Yes, reading the code will tell you exactly what it is doing. However, the code is incapable of telling you what it's supposed to be doing.
“自我记录代码”理论存在一个悲剧性的缺陷。是的,阅读代码将告诉您它到底在做什么。但是,代码无法告诉您它应该做什么。
I think it's safe to say that all bugs are caused when code is not doing what it's supposed to be doing :). So if we add some key comments to provide maintainers with enough information to know what a piece of code is supposed to be doing, then we have given them the ability to fix a whole lot of bugs.
我认为可以肯定地说,当代码没有做它应该做的事情时,所有错误都会引起:)。因此,如果我们添加一些关键注释来为维护者提供足够的信息来了解一段代码应该做什么,那么我们就已经让他们能够修复大量的错误。
That leaves us with the question of how many comments to put in. If you put in too many comments, things become tedious to maintain and the comments will inevitably be out of date with the code. If you put in too few, then they're not particularly useful.
这就留下了我们要提出多少评论的问题。如果你提出太多评论,那么维护这些事情会变得乏味,而且评论将不可避免地与代码过时。如果你投入太少,那么它们并不是特别有用。
I've found regular comments to be most useful in the following places:
我发现定期评论在以下地方最有用:
1) A brief description at the top of a .h or .cpp file for a class explaining the purpose of the class. This helps give maintainers a quick overview without having to sift through all of the code.
1).h或.cpp文件顶部的简要说明,用于解释课程目的的课程。这有助于维护人员快速浏览,而无需筛选所有代码。
2) A comment block before the implementation of a non-trivial function explaining the purpose of it and detailing its expected inputs, potential outputs, and any oddities to expect when calling the function. This saves future maintainers from having to decipher entire functions to figure these things out.
2)在执行非平凡函数之前的注释块,解释其目的并详细说明其预期输入,潜在输出以及调用函数时预期的任何奇怪之处。这使得未来的维护者不必破译整个功能来解决这些问题。
Other than that, I tend to comment anything that might appear confusing or odd to someone. For example: "This array is 1 based instead of 0 based because of blah blah".
除此之外,我倾向于评论任何可能对某人感到困惑或奇怪的事情。例如:“由于等等,这个数组是基于1而不是基于0”。
Well written, well placed comments are invaluable. Bad comments are often worse than no comments. To me, lack of any comments at all indicates laziness and/or arrogance on the part of the author of the code. No matter how obvious it is to you what the code is doing or how fantastic your code is, it's a challenging task to come into a body of code cold and figure out what the heck is going on. Well done comments can make a world of difference getting someone up to speed on existing code.
写得好,评价良好的评论非常宝贵。糟糕的评论往往比没有评论更糟糕。对我来说,没有任何评论表明代码作者的懒惰和/或傲慢。无论你对代码的作用有多么明显,或者你的代码有多么美妙,进入一个代码体并且弄清楚它到底发生了什么是一项具有挑战性的任务。做得好的评论可以让人们加快现有代码的速度。
#2
I've always liked Refactoring's take on commenting:
我一直很喜欢Refactoring的评论:
The reason we mention comments here is that comments often are used as a deodorant. It's surprising how often you look at thickly commented code and notice that the comments are there because the code is bad.
我们在这里提到评论的原因是评论经常被用作除臭剂。令人惊讶的是,您经常查看厚度注释的代码,并注意到注释是存在的,因为代码很糟糕。
Comments lead us to bad code that has all the rotten whiffs we've discussed in the rest of this chapter. Our first action is to remove the bad smells by refactoring. When we're finished, we often find that the comments are superfluous.
评论引导我们看到错误的代码,这些代码包含了我们在本章其余部分讨论过的所有腐烂的气味。我们的第一个行动是通过重构消除难闻的气味。当我们完成时,我们经常发现评论是多余的。
As controversial as that is, it's rings true for the code I've read. To be fair, Fowler isn't saying to never comment, but to think about the state of your code before you do.
尽管有争议,但对于我读过的代码来说,这是真的。公平地说,福勒并不是说永远不会发表评论,而是在你做之前考虑代码的状态。
#3
You need documentation (in some form; not always comments) for a local understanding of the code. Code by itself tells you what it does, if you read all of it and can keep it all in mind. (More on this below.) Comments are best for informal or semiformal documentation.
您需要文档(以某种形式;并不总是注释)以便本地理解代码。代码本身会告诉您它的作用,如果您阅读了所有内容并且可以牢记这一点。 (更多内容见下文。)评论最适合非正式或半正式文档。
Many people say comments are a code smell, replaceable by refactoring, better naming, and tests. While this is true of bad comments (which are legion), it's easy to jump to concluding it's always so, and hallelujah, no more comments. This puts all the burden of local documentation -- too much of it, I think -- on naming and tests.
许多人说评论是代码气味,可以通过重构,更好的命名和测试来替换。虽然糟糕的评论(即军团)也是如此,但很容易跳到总结如此,哈利路亚,没有更多的评论。这使得本地文档的所有负担 - 我认为太多 - 在命名和测试上。
Document the contract of each function and, for each type of object, what it represents and any constraints on a valid representation (technically, the abstraction function and representation invariant). Use executable, testable documentation where practical (doctests, unit tests, assertions), but also write short comments giving the gist where helpful. (Where tests take the form of examples, they're incomplete; where they're complete, precise contracts, they can be as much work to grok as the code itself.) Write top-level comments for each module and each project; these can explain conventions that keep all your other comments (and code) short. (This supports naming-as-documentation: with conventions established, and a place we can expect to find subtleties noted, we can be confident more often that the names tell all we need to know.) Longer, stylized, irritatingly redundant Javadocs have their uses, but helped generate the backlash.
记录每个函数的契约,并为每种类型的对象记录它代表的内容以及对有效表示的任何约束(技术上,抽象函数和表示不变)。在可行的情况下使用可执行的,可测试的文档(doctests,单元测试,断言),但也要写一些简短的评论,给出有用的要点。 (如果测试采用示例的形式,它们是不完整的;如果它们是完整的,精确的合同,它们可以像代码本身那样进行工作。)为每个模块和每个项目编写*注释;这些可以解释保持所有其他注释(和代码)简短的约定。 (这支持命名为文档:建立了约定,并且我们可以期待找到微妙的地方,我们可以更频繁地确信这些名称告诉我们需要知道的所有内容。)更长,风格化,烦躁多余的Javadocs有他们的使用,但帮助产生反弹。
(For instance, this:
(例如,这个:
Perform an n-fold frobulation.
@param n the number of times to frobulate
@param x the x-coordinate of the center of frobulation
@param y the y-coordinate of the center of frobulation
@param z the z-coordinate of the center of frobulation执行n次fr选。 @param n frobulate @param的次数x frobulation中心的x坐标@param y frobulation中心的y坐标@param z frobulation中心的z坐标
could be like "Frobulate n times around the center (x,y,z)." Comments don't have to be a chore to read and write.)
可能就像“围绕中心(x,y,z)发生n次。”评论不一定是读写的苦差事。)
I don't always do as I say here; it depends on how much I value the code and who I expect to read it. But learning how to write this way made me a better programmer even when cutting corners.
我不像我在这里说的那样做;这取决于我对代码的重视程度以及我希望阅读的代码。但是学习如何用这种方式写作让我成为一个更好的程序员,即使是在偷工减料。
Back on the claim that we document for the sake of local understanding: what does this function do?
回到我们为了本地理解而记录的声明:这个函数有什么作用?
def is_even(n): return is_odd(n-1)
Tests if an integer is even? If is_odd()
tests if an integer is odd, then yes, that works. Suppose we had this:
测试整数是否均匀?如果is_odd()测试一个整数是奇数,那么是的,这是有效的。假设我们有这个:
def is_odd(n): return is_even(n-1)
The same reasoning says this is_odd()
tests if an integer is odd. Put them together, of course, and neither works, even though each works if the other does. Change it a bit and we'd have code that does work, but only for natural numbers, while still locally looking like it works for integers. In microcosm that's what understanding a codebase is like: tracing dependencies around in circles to try to reverse-engineer assumptions the author could have explained in a line or two if they'd bothered. I hate the expense of spirit thoughtless coders have put me to this way over the past couple of decades: oh, this method looks like it has the side effect of farbuttling the warpcore... always? Well, if odd crobuncles desaturate, at least; do they? Better check all the crobuncle-handling code... which will pose its own challenges to understanding. Good documentation cuts this O(n) pointer-chasing down to O(1): e.g. knowing a function's contract and the contracts of the things it explicitly uses, the function's code should make sense with no further knowledge of the system. (Here, contracts saying is_even()
and is_odd()
work on natural numbers would tell us that both functions need to test for n==0
.)
同样的推理说这个is_odd()测试一个整数是奇数。当然,将它们组合在一起并且都不起作用,即使每个都有效也是如此。稍微更改一下,我们的代码可以正常工作,但仅适用于自然数字,而本地看起来仍适用于整数。在微观世界中,这就是理解代码库的方式:跟踪圈内的依赖关系,试图对假设进行反向工程,如果他们感到烦恼,作者可能会在一两行中解释。在过去的几十年里,我讨厌精神上没有精神的程序员让我这样做的费用:噢,这种方法看起来好像它具有挫败战争核心的副作用......总是?好吧,如果奇怪的crobuncles去饱和,至少;他们呢?更好地检查所有crobuncle处理代码......这将对理解提出自己的挑战。好的文档会将这个O(n)指针切换为O(1):例如:知道一个函数的契约和它明确使用的东西的契约,函数的代码应该没有进一步的系统知识。 (这里,关于自然数的is_even()和is_odd()的合同会告诉我们两个函数都需要测试n == 0。)
#4
My only real rule is that comments should explain why code is there, not what it is doing or how it is doing it. Those things can change, and if they do the comments have to be maintained. The purpose the code exists in the first place shouldn't change.
我唯一真正的规则是评论应该解释为什么代码存在,而不是它正在做什么或它是如何做的。这些事情可以改变,如果他们这样做,则必须保持评论。代码首先存在的目的不应该改变。
#5
the purpose of comments is to explain the context - the reason for the code; this, the programmer cannot know from mere code inspection. For example:
评论的目的是解释背景 - 代码的原因;这,程序员无法从单纯的代码检查中知道。例如:
strangeSingleton.MoveLeft(1.06);
badlyNamedGroup.Ignite();
who knows what the heck this is for? but with a simple comment, all is revealed:
谁知道这是为了什么?但只有简单的评论,所有内容都显示出来:
//when under attack, sidestep and retaliate with rocket bundles
strangeSingleton.MoveLeft(1.06);
badlyNamedGroup.Ignite();
seriously, comments are for the why, not the how, unless the how is unintuitive.
严肃地说,评论是为什么,而不是如何,除非如何不直观。
#6
While I agree that code should be self-readable, I still see a lot of value in adding extensive comment blocks for explaining design decisions. For example "I did xyz instead of the common practice of abc because of this caveot ..." with a URL to a bug report or something.
虽然我同意代码应该是自我可读的,但我仍然认为在添加广泛的注释块以解释设计决策方面有很多价值。例如“我做了xyz而不是abc的常见做法,因为这个洞穴......”带有错误报告的URL或其他东西。
I try to look at it as: If I'm dead and gone and someone straight out of college has to fix a bug here, what are they going to need to know?
我试着将其视为:如果我已经死了并且已经离开并且大学毕业的人必须在这里修复一个错误,他们需要知道什么?
#7
In general I see comments used to explain poorly written code. Most code can be written in a way that would make comments redundant. Having said that I find myself leaving comments in code where the semantics aren't intuitive, such as calling into an API that has strange or unexpected behavior etc...
一般来说,我看到用于解释写得不好的代码的注释。大多数代码都可以以使注释冗余的方式编写。话虽如此,我发现自己在代码中留下了注释,其中语义不直观,例如调用具有奇怪或意外行为等的API ......
#8
I also generally subscribe to the self-documenting code idea, so I think your developer friend gives good advice, and I won't repeat that, but there are definitely many situations where comments are necessary.
我通常也会订阅自我记录代码的想法,所以我认为你的开发者朋友提供了很好的建议,我不会重复,但肯定有很多情况需要注释。
A lot of times I think it boils down to how close the implementation is to the types of ordinary or easy abstractions that code-readers in the future are going to be comfortable with or more generally to what degree the code tells the entire story. This will result in more or fewer comments depending on the type of programming language and project.
很多时候,我认为它归结为实现与普通或简单抽象的类型有多接近,未来的代码阅读器将会感到舒适,或者更普遍的是代码告诉整个故事的程度。这将导致更多或更少的注释,具体取决于编程语言和项目的类型。
So, for example if you were using some kind of C-style pointer arithmetic in an unsafe C# code block, you shouldn't expect C# programmers to easily switch from C# code reading (which is probably typically more declarative or at least less about lower-level pointer manipulation) to be able to understand what your unsafe code is doing.
因此,例如,如果您在不安全的C#代码块中使用某种C风格的指针算法,您不应期望C#程序员能够轻松地从C#代码读取切换(这可能通常更具说明性或至少更低一些 - 级别指针操作),以便能够理解您的不安全代码正在做什么。
Another example is when you need to do some work deriving or researching an algorithm or equation or something that is not going to end up in your code but will be necessary to understand if anyone needs to modify your code significantly. You should document this somewhere and having at least a reference directly in the relevant code section will help a lot.
另一个例子是当你需要做一些工作来推导或研究一个算法或方程式或者某些不会在你的代码中结束的东西,但是有必要了解是否有人需要显着修改你的代码。你应该在某个地方记录这一点,并且在相关的代码部分中至少直接引用将有很大帮助。
#9
I don't think it matters how many or how few comments your code contains. If your code contains comments, they have to maintained, just like the rest of your code.
我认为您的代码包含多少或几个评论并不重要。如果您的代码包含注释,则必须维护它们,就像代码的其余部分一样。
EDIT: That sounded a bit pompous, but I think that too many people forget that even the names of the variables, or the structures we use in the code, are all simply "tags" - they only have meaning to us, because our brains see a string of characters such as customerNumber
and understand that it is a customer number. And while it's true that comments lack any "enforcement" by the compiler, they aren't so far removed. They are meant to convey meaning to another person, a human programmer that is reading the text of the program.
编辑:这听起来有点浮夸,但我认为有太多人忘记即使是变量的名称,或者我们在代码中使用的结构,都只是“标签” - 它们只对我们有意义,因为我们的大脑查看一串字符,例如customerNumber,并了解它是一个客户编号。尽管评论缺乏编译器的任何“强制执行”,但它们并没有被删除。它们旨在向另一个人传达意义,一个正在阅读该程序文本的人类程序员。
#10
If the code is not clear without comments, first make the code a clearer statement of intent, then only add comments as needed.
如果没有注释的代码不清楚,首先使代码更清晰的意图声明,然后只根据需要添加注释。
Comments have their place, but primarily for cases where the code is unavoidably subtle or complex (inherent complexity is due to the nature of the problem being solved, not due to laziness or muddled thinking on the part of the programmer).
评论有其自己的位置,但主要用于代码不可避免地微妙或复杂的情况(固有的复杂性是由于问题的性质得到解决,而不是由于程序员的懒惰或混乱的思维)。
Requiring comments and "measuring productivity" in lines-of-code can lead to junk such as:
在代码行中要求注释和“衡量生产力”可能导致垃圾,例如:
/*****
*
* Increase the value of variable i,
* but only up to the value of variable j.
*
*****/
if (i < j) {
++i;
} else {
i = j;
}
rather than the succinct (and clear to the appropriately-skilled programmer):
而不是简洁(并且适当熟练的程序员清楚):
i = Math.min(j, i + 1);
YMMV
#11
The vast majority of my commnets are at the class-level and method-level, and I like to describe the higher-level view instead of just args/return value. I'm especially careful to describe any "non-linearities" in the function (limits, corner cases, etc) that could trip up the unwary.
我的绝大多数通信都是在类级别和方法级别,我喜欢描述更高级别的视图而不仅仅是args / return值。我特别小心地描述了函数中的任何“非线性”(限制,极端情况等),这些都可能会让人不知所措。
Typically I don't comment inside a method, except to mark "FIXME" items, or very occasionally some sort of "here be monsters" gotcha that I just can't seem to clean up, but I work very hard to avoid those. As Fowler says in Refactoring, comments tend to indicate smally code.
通常情况下我不会在方法内部发表评论,除了标记“FIXME”项目,或者偶尔会出现某些“这里是怪物”,我似乎无法清理,但我努力避免这些。正如Fowler在Refactoring中所说,评论往往表明代码很少。
#12
Comments are part of code, just like functions, variables and everything else - and if changing the related functionality the comment must also be updated (just like function calls need changing if function arguments change).
注释是代码的一部分,就像函数,变量和其他所有东西一样 - 如果更改相关功能,注释也必须更新(就像函数调用需要更改,如果函数参数更改)。
In general, when programming you should do things once in one place only.
一般来说,编程时你应该只在一个地方做一次。
Therefore, if what code does is explained by clear naming, no comment is needed - and this is of course always the goal - it's the cleanest and simplest way.
因此,如果通过明确命名解释了什么代码,则不需要评论 - 这当然也是目标 - 这是最干净,最简单的方法。
However, if further explanation is needed, I will add a comment, prefixed with INFO, NOTE, and similar...
An INFO: comment is for general information if someone is unfamiliar with this area.
A NOTE: comment is to alert of a potential oddity, such as a strange business rule / implementation.
If I specifically don't want people touching code, I might add a WARNING: or similar prefix.
但是,如果需要进一步说明,我将添加一个注释,前缀为INFO,NOTE和类似的...一个INFO:注释用于一般信息,如果有人不熟悉这个区域。注意:注释是警告潜在的奇怪,例如奇怪的业务规则/实现。如果我特别不希望人们接触代码,我可能会添加一个警告:或类似的前缀。
What I don't use, and am specifically opposed to, are changelog-style comments - whether inline or at the head of the file - these comments belong in the version control software, not the sourcecode!
我不使用,并且特别反对的是更改日志样式的注释 - 无论是内联还是文件的头部 - 这些注释属于版本控制软件,而不是源代码!
#13
I prefer to use "Hansel and Gretel" type comments; little notes in the code as to why I'm doing it this way, or why some other way isn't appropriate. The next person to visit this code will probably need this info, and more often than not, that person will be me.
我更喜欢使用“Hansel and Gretel”类型的评论;代码中的小注释,为什么我这样做,或者为什么其他方式不合适。下一个访问此代码的人可能需要这些信息,而且通常情况下,那个人将是我。
#14
As a contractor I know that some people maintaining my code will be unfamiliar with the advanced features of ADO.Net I am using. Where appropriate, I add a brief comment about the intent of my code and a URL to an MSDN page that explains in more detail.
作为承包商,我知道有些人维护我的代码将不熟悉我正在使用的ADO.Net的高级功能。在适当的情况下,我添加了一个关于我的代码意图的简短评论和一个更详细解释的MSDN页面的URL。
I remember learning C# and reading other people's code I was often frustrated by questions like, "which of the 9 meanings of the colon character does this one mean?" If you don't know the name of the feature, how do you look it up?! (Side note: This would be a good IDE feature: I select an operator or other token in the code, right click then shows me it's language part and feature name. C# needs this, VB less so.)
我记得学习C#并阅读其他人的代码我常常对这样的问题感到沮丧,比如“结肠字符的9个含义中哪一个意味着什么?”如果您不知道该功能的名称,您如何查找?! (旁注:这将是一个很好的IDE功能:我在代码中选择一个运算符或其他标记,右键单击然后显示它的语言部分和功能名称.C#需要这个,VB不那么。)
As for the "I don't comment my code because it is so clear and clean" crowd, I find sometimes they overestimate how clear their very clever code is. The thought that a complex algorithm is self-explanatory to someone other than the author is wishful thinking.
至于“我不评论我的代码,因为它是如此清晰和干净”的人群,我发现有时他们高估了他们非常聪明的代码是多么清晰。认为复杂算法对作者以外的其他人不言自明的想法是一厢情愿的想法。
And I like @17 of 26's comment (empahsis added):
我喜欢26的评论中的第17条(empahsis补充):
... reading the code will tell you exactly what it is doing. However, the code is incapable of telling you what it's supposed to be doing.
...阅读代码将告诉你它到底在做什么。但是,代码无法告诉您它应该做什么。
#15
I very very rarely comment. MY theory is if you have to comment it's because you're not doing things the best way possible. Like a "work around" is the only thing I would comment. Because they often don't make sense but there is a reason you are doing it so you need to explain.
我很少发表评论。我的理论是,如果你必须评论它,因为你没有尽可能最好地做事。就像“解决方法”一样,我唯一会评论。因为它们通常没有意义,但是你有理由这样做,所以你需要解释。
Comments are a symptom of sub-par code IMO. I'm a firm believer in self documenting code. Most of my work can be easily translated, even by a layman, because of descriptive variable names, simple form, and accurate and many methods (IOW not having methods that do 5 different things).
评论是IMO低于标准代码的症状。我坚信自我记录代码。由于描述性变量名称,简单形式,准确和许多方法(IOW没有方法可以做5种不同的事情),我的大部分工作都可以轻松翻译,即使是外行也是如此。
#16
Comments are part of a programmers toolbox and can be used and abused alike. It's not up to you, that other programmer, or anyone really to tell you that one tool is bad overall. There are places and times for everything, including comments.
注释是程序员工具箱的一部分,可以使用和滥用。这不是由你,其他程序员或任何人真正告诉你一个工具总体上是坏的。一切都有地方和时间,包括评论。
I agree with most of what's been said here though, that code should be written so clear that it is self-descriptive and thus comments aren't needed, but sometimes that conflicts with the best/optimal implementation, although that could probably be solved with an appropriately named method.
我同意这里所说的大部分内容,但是代码应该写得如此清晰,以至于它是自我描述性的,因此不需要注释,但有时会与最佳/最佳实现冲突,尽管这可能通过一个适当命名的方法。
#17
I agree with the self-documenting code theory, if I can't tell what a peice of code is doing simply by reading it then it probably needs refactoring, however there are some exceptions to this, I'll add a comment if:
我同意自我记录代码理论,如果我只是通过阅读它无法分辨代码的作用,那么它可能需要重构,但是有一些例外,我会在以下情况下添加注释:
- I'm doing something that you don't normally see
- There are major side effects or implementation details that aren't obvious, or won't be next year
- I need to remember to implement something although I prefer an exception in these cases.
- If I'm forced to go do something else and I'm having good ideas, or a difficult time with the code, then I'll add sufficient comments to tmporarily preserve my mental state
我正在做一些你通常看不到的事情
有明显的副作用或实施细节,或明年不会
我需要记住实现一些东西,尽管在这些情况下我更喜欢异常。
如果我*去做其他事情并且我有很好的想法,或者代码很难,那么我会添加足够的评论来暂时保留我的精神状态
#18
Most of the time I find that the best comment is the function or method name I am currently coding in. All other comments (except for the reasons your friend mentioned - I agree with them) feel superfluous.
大多数时候我发现最好的评论是我目前编写的函数或方法名称。所有其他评论(除了你朋友提到的原因 - 我同意他们的观点)感觉多余。
So in this instance commenting feels like overkill:
所以在这种情况下,评论感觉有点矫枉过正:
/*
* this function adds two integers
*/
int add(int x, int y)
{
// add x to y and return it
return x + y;
}
because the code is self-describing. There is no need to comment this kind of thing as the name of the function clearly indicates what it does and the return statement is pretty clear as well. You would be surprised how clear your code becomes when you break it down into tiny functions like this.
因为代码是自我描述的。没有必要评论这种事情,因为函数的名称清楚地表明它的作用,并且return语句也非常清楚。当你将代码细分为像这样的小函数时,你会感到惊讶。
#19
When programming in C, I'll use multi-line comments in header files to describe the API, eg parameters and return value of functions, configuration macros etc...
在C语言编程时,我将在头文件中使用多行注释来描述API,例如函数的参数和返回值,配置宏等......
In source files, I'll stick to single-line comments which explain the purpose of non-self-evident pieces of code or to sub-section a function which can't be refactored to smaller ones in a sane way. Here's an example of my style of commenting in source files.
在源文件中,我将坚持单行注释,这些注释解释了非自明的代码片段的目的,或者将一个不能以理智的方式重构为较小的函数的子函数。这是我在源文件中评论风格的一个例子。
If you ever need more than a few lines of comments to explain what a given piece of code does, you should seriously consider if what you're doing can't be done in a better way...
如果您需要多行注释来解释给定代码片段的作用,那么您应该认真考虑一下您所做的事情是否无法以更好的方式完成...
#20
I write comments that describe the purpose of a function or method and the results it returns in adequate detail. I don't write many inline code comments because I believe my function and variable naming to be adequate to understand what is going on.
我编写的注释描述了函数或方法的用途以及它返回的结果。我不会写很多内联代码注释,因为我相信我的函数和变量命名足以理解正在发生的事情。
I develop on a lot of legacy PHP systems that are absolutely terribly written. I wish the original developer would have left some type of comments in the code to describe what was going on in those systems. If you're going to write indecipherable or bad code that someone else will read eventually, you should comment it.
我在很多遗留的PHP系统上开发,这些系统写得非常糟糕。我希望原始开发人员在代码中留下某种类型的注释来描述这些系统中发生的事情。如果您要编写其他人最终会阅读的难以理解或错误的代码,您应该对其进行评论。
Also, if I am doing something a particular way that doesn't look right at first glance, but I know it is because the code in question is a workaround for a platform or something like that, then I'll comment with a WARNING comment.
另外,如果我正在做一些看起来不太正确的特定方式,但我知道这是因为有问题的代码是平台的解决方法或类似的东西,那么我将使用警告评论进行评论。
#21
Sometimes code does exactly what it needs to do, but is kind of complicated and wouldn't be immediately obvious the first time someone else looked at it. In this case, I'll add a short inline comment describing what the code is intended to do.
有时代码确实完成了它需要做的事情,但有点复杂,并且在第一次有人看到它时不会立即明显。在这种情况下,我将添加一个简短的内联注释,描述代码的目的。
I also try to give methods and classes documentation headers, which is good for intellisense and auto-generated documentation. I actually have a bad habit of leaving 90% of my methods and classes undocumented. You don't have time to document things when you're in the middle of coding and everything is changing constantly. Then when you're done you don't feel like going back and finding all the new stuff and documenting it. It's probably good to go back every month or so and just write a bunch of documentation.
我还尝试给出方法和类文档头文件,这对于intellisense和自动生成的文档很有用。我实际上有一个坏习惯,就是让90%的方法和课程都没有记录。当您处于编码过程中并且一切都在不断变化时,您没有时间记录事物。然后,当你完成后,你不想回去找到所有新东西并记录下来。每个月左右回来并写一堆文档可能会很好。
#22
Here's my view (based on several years of doctoral research):
这是我的观点(基于几年的博士研究):
There's a huge difference between commenting functions (sort of a black box use, like JavaDocs), and commenting actual code for someone who will read the code ("internal commenting").
注释函数(类似黑盒使用,如JavaDocs)和为读取代码的人(“内部注释”)评论实际代码之间存在巨大差异。
Most "well written" code shouldn't require much "internal commenting" because if it performs a lot then it should be broken into enough function calls. The functionality for each of these calls is then captured in the function name and in the function comments.
大多数“写得好”的代码不应该需要太多的“内部评论”,因为如果它执行了很多,那么它应该分解成足够的函数调用。然后,在函数名称和函数注释中捕获每个调用的功能。
Now, function comments are indeed the problem, and in some ways your friend is right, that for most code there is no economical incentive for complete specifications the way that popular APIs are documented. The important thing here is to identify what are the "directives": directives are those information pieces that directly affect clients, and require some direct action (and are often unexpected). For example, X must be invoked before Y, don't call this from outside a UI thread, be aware that this has a certain side effect, etc. These are the things that are really important to capture.
现在,函数注释确实是问题所在,并且在某些方面你的朋友是对的,对于大多数代码来说,对于完整的规范没有经济上的激励,就像流行的API被记录一样。这里重要的是确定什么是“指令”:指令是那些直接影响客户的信息片段,需要一些直接的操作(并且通常是意外的)。例如,X必须在Y之前调用,不要从UI线程外部调用它,要知道这有一定的副作用,等等。这些是捕获非常重要的事情。
Since most people never read full function documentations, and skim what they do read, you can actually increase the chances of awareness by capturing only the directives rather than the whole description.
由于大多数人从不阅读完整的功能文档,并浏览他们所阅读的内容,因此实际上可以通过仅捕获指令而不是整个描述来增加意识的机会。
#23
I comment as much as needed - then, as much as I will need it a year later.
我尽可能多地评论 - 然后,就像我一年后需要的那样。
#24
We add comments which provide the API reference documentation for all public classes / methods / properties / etc... This is well worth the effort because XML Documentation in C# has the nice effect of providing IntelliSense to users of these public APIs. .NET 4.0's code contracts will enable us to improve further on this practice.
我们添加注释,为所有公共类/方法/属性/等提供API参考文档......这非常值得,因为C#中的XML文档具有为这些公共API的用户提供IntelliSense的良好效果。 .NET 4.0的代码合同将使我们能够进一步改进这种做法。
As a general rule, we do not document internal implementations as we write code unless we are doing something non-obvious. The theory is that while we are writing new implementations, things are changing and comments are more likely than not to be wrong when the dust settles.
作为一般规则,我们不会在编写代码时记录内部实现,除非我们做了一些不明显的事情。理论是,当我们正在编写新的实现时,事情正在发生变化,当尘埃落定时,评论更有可能不会出错。
When we go back in to work on an existing piece of code, we add comments when we realize that it's taking some thought to figure out what in the heck is going on. This way, we wind up with comments where they are more likely to be correct (because the code is more stable) and where they are more likely to be useful (if I'm coming back to a piece of code today, it seems more likely that I might come back to it again tomorrow).
当我们回到现有的代码片段时,我们会在我们意识到它正在考虑找出正在发生的事情时添加注释。通过这种方式,我们最终得出的评论更可能是正确的(因为代码更稳定),并且它们更有可能是有用的(如果我今天回到一段代码,它似乎更多可能我明天可能会再次回到它。
#25
My approach:
Comments bridge the gap between context / real world and code. Therefore, each and every single line is commented, in correct English language.
评论弥合了上下文/现实世界和代码之间的差距。因此,每一行都以正确的英语进行评论。
I DO reject code that doesn't observe this rule in the strictest possible sense.
我拒绝在最严格意义上不遵守此规则的代码。
Usage of well formatted XML - comments is self-evident.
使用格式良好的XML - 注释是不言而喻的。
Sloppy commenting means sloppy code!
邋comment的评论意味着草率的代码!
#26
Here's how I wrote code:
这是我编写代码的方式:
if (hotel.isFull()) {
print("We're fully booked");
} else {
Guest guest = promptGuest();
hotel.checkIn(guest);
}
here's a few comments that I might write for that code:
这里有一些我可能会为该代码编写的评论:
// if hotel is full, refuse checkin, otherwise
// prompt the user for the guest info, and check in the guest.
If your code reads like a prose, there is no sense in writing comments that simply repeats what the code reads since the mental processing needed for reading the code and the comments would be almost equal; and if you read the comments first, you will still need to read the code as well.
如果你的代码看起来像散文,那么编写注释只是重复代码读取的内容是没有意义的,因为阅读代码所需的心理处理和注释几乎相同;如果您先阅读注释,您仍需要阅读代码。
On the other hand, there are situations where it is impossible or extremely difficult to make the code looks like a prose; that's where comment could patch in.
另一方面,有些情况下,使代码看起来像散文是不可能或极难的;那是评论可以补丁的地方。