编写代码注释_注释什么以及何时编写更好的代码

编写代码注释

Quality code usually consists of good comments that help us understand the code better. But what are good comments? When should you comment the code? What makes a code comment a great comment?

质量代码通常包含良好的注释,可以帮助我们更好地理解代码。 但是什么是好的评论? 您什么时候应该注释代码? 是什么使代码注释成为出色的注释?

Hopefully, in this short post, we will answer all the above questions and more.

希望在这篇简短的文章中,我们将回答以上所有问题以及更多问题。

The purpose of commenting is to help the reader know as much as the writer did.

评论的目的是帮助读者像作家一样了解。

At the time of writing the code, you have a lot of information in your head. When other people read your code or even you a few months later, that information is lost — all you are left with is the code you’ve written.

在编写代码时,您掌握了很多信息。 当其他人甚至几个月后阅读您的代码时,这些信息就会丢失—您所剩下的就是编写的代码。

In this post, we will go over what to write down, what not to write down and how to pack as much information as possible in a short comment.

在这篇文章中,我们将讨论写下的内容,不写下的内容以及如何在简短的评论中尽可能多地打包信息。

We will take a look at the following things:

我们将看一下以下内容:

  • What not to comment

    什么没什么好评论
  • What to comment

    评论什么
  • Put yourself in the reader's shoes

    把自己放在读者的鞋子里

什么没什么好评论 (What not to comment)

When other people read our code, a comment takes away time and attention from the actual code. That said the comment should provide valuable information to the reader otherwise the time spent reading the comment was worthless. So what is the difference between valuable and worthless comment?

当其他人阅读我们的代码时,注释会占用实际代码的时间和精力。 也就是说,评论应该为读者提供有价值的信息,否则阅读评论所花费的时间就毫无价值。 那么,有价值的评论和毫无价值的评论有什么区别?

Let’s see an example of worthless comments in the code:

让我们看一下代码中毫无价值的注释的示例:

// User class definition
class User {
// Constructor
constructor() {}
// Get user's first name
getFirstName() {
return this.firstName;
} // Set user's age
setAge(age) {
this.age = age
}
}

All these comments are worthless because they don't provide any additional value or information to the reader.

所有这些评论都是毫无价值的,因为它们没有为读者提供任何其他价值或信息。

Don’t comment on facts that can be derived quickly from the code itself.

不要评论可以从代码本身快速得出的事实。

不要仅仅为了评论而发表评论 (Don’t comment just for the sake of commenting)

This should be self-explanatory. Don’t comment your code just because you are used to putting comments on every line. Other developers should understand your intentions just by going through the actual code.

这应该是不言自明的。 不要仅仅因为习惯于在每一行添加注释而注释掉您的代码。 其他开发人员应仅通过阅读实际代码来了解您的意图。

不要评论坏名字 (Don’t comment bad names)

This one is a bit trickier. From time to time everyone names their variable or function with a bad name, but a comment shouldn't be the fix for a bad naming — fix the name instead.

这个有点棘手。 每个人都时不时地用变量名来命名变量或函数,但注释不应该是错误命名的解决方法,而应改名。

Let’s look at a simple example:

让我们看一个简单的例子:

// Replace encoded characthers in a string
function cleanString(string) { ... }

This is a simple example with a short comment, but when dealing with something way more complex you can imagine how long it would take for someone to explain what the code does. All this could be avoided if the function was better named. Since we know that all it does is to replace encoded characters in the given string, a more self-documented name could be decodeString .

这是一个带有简短注释的简单示例,但是当处理更复杂的内容时,您可以想象某人解释该代码将花费多长时间。 如果对函数进行更好的命名,可以避免所有这些情况。 由于我们知道它所做的全部就是替换给定字符串中的编码字符,因此可以更自记录的名称是decodeString

评论什么 (What to comment)

Now that you know what not to comment, let’s take a look at what you should be commenting but often doesn't. A lot of good comments can come out by simply writing down a few words from your thought process when developing a piece of code. As mentioned at the beginning, you have a lot of additional information about the problem you are solving, and if this information doesn't get written it’s lost forever.

现在您知道了什么不可以评论,让我们看一下您应该评论但经常不评论的内容。 在开发一段代码时,只需在思考过程中写下几个字就可以得出很多好的评论。 如开始时所提到的,您有许多有关要解决的问题的其他信息,如果这些信息没有写好,它将永远丢失。

写下您的思考过程 (Write down your thought process)

The comment could be something as simple as your observations while developing the code.

注释可能和您在开发代码时的观察一样简单。

Here is a simple example:

这是一个简单的示例:

// This function shouldn't have await since we don't need the result.

This comment teaches the reader we shouldn't wait for the execution of this code. When dealing with a code that has await on every function call this might be helpful to document since it might be mistaken for a bug.

此注释告诉读者我们不要等待该代码的执行。 在处理await每个函数调用的代码时,这可能会对文档记录有所帮助,因为它可能被误认为是错误。

Here is another example:

这是另一个示例:

// This call might timeout. That's OK since the data will be resent in the next invocation.

Without the comment, the reader might think there is a bug in the code and waste time trying to reproduce the bug and to fixing it.

如果没有评论,读者可能会认为代码中存在错误,并且会浪费时间来重现并修复该错误。

A comment can also contain ideas for improvements or code redesign:

注释还可以包含改进或重新设计代码的想法:

// This class is getting too big. Maybe we should create a new subclass.

评论缺陷 (Comment the flaws)

Finding the flaw or the bug in the code is sometimes more time consuming than fixing it. That's why it’s crucial for every developer to comment on the flaws they make or find in the codebase. When you know something could be improved don't be afraid to put a comment. It’s highly likely that someone else reading the code was having the same issue and knows how to fix it.

在代码中查找缺陷或错误有时比修复它更耗时。 因此,对于每个开发人员来说,评论他们在代码库中制造或发现的缺陷至关重要。 当您知道可以改进的地方时,不要害怕发表评论。 阅读该代码的其他人很有可能遇到相同的问题,并且知道如何解决它。

There a number of popular markers to mark the code:

有许多流行的标记来标记代码:

  • TODO — stuff that needs to be done

    TODO-需要完成的工作
  • HACK — mark the piece of code that is customised for a specific use case

    HACK —标记针对特定用例定制的代码段
  • FIXME — known issue

    FIXME-已知问题
  • NOTE — be aware of …

    注意—注意…

Your codebase might have specific conventions for when to use which marks. Most of the time you will see the TODO since is versatile and most well known.

您的代码库可能对何时使用哪些标记有特定的约定。 大多数时候,您会看到TODO因为它用途广泛且广为人知。

The important thing is that you should always comment on your thoughts about how code works, what could be improved, what is missing and what could potentially go wrong. It will help you and your team in the long run.

重要的是,您应该始终对代码的工作方式,可以改进的地方,缺失的地方以及可能出错的地方发表评论。 从长远来看,它将为您和您的团队提供帮助。

评论您的常数 (Comment your constants)

When defining a constant there is usually a background for what the constant does or why it has that specific value. For example, you might see a constant like this:

当定义一个常数时,通常会有一个背景说明该常数做什么或为什么具有该特定值。 例如,您可能会看到这样的常量:

const NUM_OF_WORKERS = 8

At first glance, you might think this constant does not need a comment. But why is the value for this particular constant set to eight? The person working on this code definitely has the answer — why not embed it into the code in the first place. The code could look something like this:

乍一看,您可能会认为此常量不需要注释。 但是为什么将这个特定常数的值设置为8? 编写此代码的人肯定有答案-为什么首先不将其嵌入到代码中。 代码看起来像这样:

// Set to 8 since we encounter some problems with concurrency when // working with more workers
const NUM_OF_WORKERS = 8

Now the person reading the code has insight on how the value was adjusted and set to this specific value.

现在,阅读代码的人可以洞悉如何调整该值并将其设置为该特定值。

Sometimes the value of the constant is not important at all. Commenting this could be still useful since the person reading the code immediately knows that the constant could be changed without causing any harm.

有时,常数的值根本不重要。 注释这可能仍然有用,因为阅读代码的人立即知道可以更改该常数而不会造成任何损害。

// Set to 100 since is a reasonable limit - noone will buy more that // 100 items anyway. Still could be changed in the future
const MAX_CART_SIZE = 100

There are also some constants that don’t need comments. For example SECONDS_IN_AN_HOUR — the name is clear enough.

还有一些不需要注释的常量。 例如SECONDS_IN_AN_HOUR名称足够清楚。

Use common sense when deciding when to comment on your constants. Is the name clear enough or does it need an additional explanation?

在决定何时对常量进行注释时,请使用常识。 名称是否足够清楚,或者需要其他说明?

把自己放在读者的鞋子里 (Put yourself in the reader’s shoes)

When deciding what to comment imagine what your code looks like to an outsider. Is the code clear, is the problem the code is solving clear, is the solution clear, etc. This technique will not only help the readers to understand your code but also make you a better programmer. You will subconsciously think about the clarity of your code and therefore write better code.

在决定发表评论时,请想象一下您的代码对局外人是什么样的。 代码是否清晰,代码正在解决的问题是否清晰,解决方案的清晰程度等。此技术不仅可以帮助读者理解您的代码,而且可以使您成为一个更好的程序员。 您将下意识地考虑代码的清晰度,因此编写更好的代码。

预期可能的问题 (Anticipating likely questions)

When someone else reads your code, there are parts that are likely to make them think — What? Why? Your job is to put a comment at those parts and answers there question in advanced.

当其他人阅读您的代码时,有些部分可能会让他们思考-什么? 为什么? 您的工作是在这些部分中发表评论,并在其中预先回答问题。

For example:

例如:

function clearArray(array) {
array.length = 0
}

Why is this code setting length of the array to zero? Why not instead just set the array to an empty array like this: array = []

为什么此代码将数组的长度设置为零? 为什么不将其设置为空数组呢? array = []

In JavaScript, the upper statement creates a new empty array. If you have a reference to the variable array anywhere in the code, the value will remain unchanged. On the other hand when you set the length of the array to zero, even if there are references to the array in your code, values will be changed.

在JavaScript中,upper语句创建一个新的空数组。 如果在代码中的任何地方都引用了变量array ,则该值将保持不变。 另一方面,将数组的长度设置为零时,即使代码中存在对该数组的引用,其值也会更改。

大图 (Big picture)

One of the bigger challenges for the new team members is to understand the big picture — how data flows through the system, where the entry points are, what is the expected output, etc. The person who designed the system often skips these comments.

新团队成员面临的最大挑战之一就是要了解全局—数据如何在系统中流动,切入点在哪里,预期输出是什么等。设计系统的人员经常会跳过这些评论。

When designing the system ask yourself: if a new team member joins your team and sits next to you, what question will he/she be asking. Another great exercise to find out what are the unclear parts is to explain the codebase to your teammate — were there any questions? You should probably put a comment on those parts.

在设计系统时,请问自己:如果有新的团队成员加入您的团队并坐在您旁边,他/她将问什么问题。 找出不清楚部分的另一个好方法是向您的队友解释代码库-是否有任何问题? 您可能应该在这些部分上发表评论。

The key when documenting the big picture in your code is to keep your comments short. A few well-chosen sentences should be enough to explain what the code is doing. These comments should only be a guide to the person reading the code, formal in-depth documentation should be written separately.

在代码中记录大图的关键是使注释简短。 一些精心选择的句子应该足以解释代码的作用。 这些注释仅是阅读代码的人员的指南,正式的深入文档应单独编写。

摘要 (Summary)

The purpose of a comment is to help the reader know what the writer of the code knew at the time of writing the code. Comments should be short but useful. They should give the reader insights about the code and answer any confusion — what the code does and why.

注释的目的是帮助读者了解代码编写者在编写代码时所了解的内容。 评论应该简短但有用。 他们应该为读者提供有关代码的见解,并回答任何混淆-代码做什么以及为什么。

Writing good comments is not easy. Most of the programmers usually don't like to write comments, but with enough practice, you will find adding a comment is not that hard and time-consuming. Also once you get the grasp of value those short comments provide, commenting the code will become a no brainer to you.

写好的评论并不容易。 大多数程序员通常不喜欢编写注释,但是通过充分的实践,您会发现添加注释并不那么麻烦和费时。 同样,一旦您掌握了这些简短注释所提供的价值,对代码进行注释就不会为您带来麻烦。

什么不评论: (What not to comment:)

  • Facts

    事实
  • Fixes for bad names

    修复不良名称

评论什么 (What to comment)

  • Insights about the code

    关于代码的见解
  • Flaws and knows bugs

    缺陷并知道错误
  • Behind the scenes of the constants

    常量的背后

记住 (Keep in mind)

  • What parts of the code are unclear

    代码的哪些部分不清楚
  • Surprising behaviour

    令人惊讶的行为
  • Big picture

    大图

If you have any comments or additional tips, please leave them in the comment section!

如果您有任何意见或其他提示,请将其留在评论部分!

You should also read my previous post on how to better name your functions and variables here:

您还应该阅读我以前的文章,关于如何在此处更好地命名函数和变量:

翻译自: https://medium.com/swlh/what-to-comment-and-when-write-better-code-2451f9af08e4

编写代码注释

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值