Home Database Mysql Tutorial 注释代码的13技巧

注释代码的13技巧

Jun 07, 2016 pm 03:11 PM
code author publish Skill Comment

本文发表在作者José M. Aguilar的博客Variable Not Found,后来由Timm Martin翻译成英文发表在DevTopics上。 以下是如何注释代码的13tips,它们会在日后帮助你更容易理解和维护代码。 1. Comment each level(每个级别的注释有统一的风格) 注释每一个代码

本文发表在作者José M. Aguilar的博客Variable Not Found,后来由Timm Martin翻译成英文发表在DevTopics上。

以下是如何注释代码的13tips,它们会在日后帮助你更容易理解和维护代码。

1. Comment each level(每个级别的注释有统一的风格)

注释每一个代码块,并且在各个级别的代码块上,要使用统一的注释方法。例如:

对于类,应包含简单的描述、作者以及最近的更改日期 
对于方法,应包含目的的描述、功能、参数以及返回值

使用统一的注释规则对于一个团队是非常重要的。当然,更加推荐使用注释的约定和工具(例如,C#的XML或Java的Javadoc),它们会是注释变得更加容易。

2. Use paragraph comments(对段落注释)

将代码块分成若干完成独立功能的"段落",并在每个"段落"前添加注释,向读者说明"即将发生什么"。

// Check that all data records

// are correct

foreach (Record record in records)

{

if (rec.checkStatus()==Status.OK)

{

. . .

}

}

// Now we begin to perform

// transactions

Context ctx = new ApplicationContext();

ctx.BeginTransaction();

. . .

3. Align comments in consecutive lines(对齐注释行)

对于拥有后缀式注释的多行代码,排版注释代码,使各行注释对齐到同一列。

const MAX_ITEMS = 10; // maximum number of packets

const MASK = 0x1F; // mask bit TCP

一些开发人员使用tab来对齐注释,有些则使用空格。但是由于tab在不同的编辑器或者IDE上会有所不同,最好还是使用空格。

4. Don't insult the reader's intelligence(不要侮辱读者的智商)

不要写没用的注释,例如:

if (a == 5) // if a equals 5

counter = 0; // set the counter to zero

写这种无用的注释不但浪费你的时间,而且读者在读这种很容易理解的代码时,很容易被你的注释转移注意力,浪费了时间。

5. Be polite(要有礼貌)

不要写不礼貌的注释代码,例如"注意,愚蠢的使用者输入了一个负数",或者"修正由于最初的开发者的可怜且愚蠢的编码所造成的副作用"。这样的注释冒犯了作者,而且你并不知道谁会在将来读到这段注释--你老板、客户或者是你在注释中冒犯的那个可怜且愚蠢的开发人员。

6. Get to the point(简明扼要)

不要在注释中写的过多,不要写玩笑、诗和冗长的话。总之,注释需要简单直接。

7. Use a consistent style(风格一致)

一些人认为注释应该能让非程序员也能看懂,但是也有些人认为注释仅仅是指导程序员的。不管怎么说,像《Successful Strategies for Commenting Code》中所说,真正重要的是注释始终面向同一个读者,在这点上,应该保持一致。个人认为,我很怀疑会有非程序人员阅读代码,所以应该把阅读注释的对象定位为开发人员。

int Estimate(int x, int y)

{

// TODO: implement the calculations

return 0;

}

9. Comment code while writing it(写代码的同时,完成注释)

写代码的同时添加注释,因为此时你的思路最为清晰。如果你把注释的任务留到最后,那么你相当于经历了两次编码。"我没有时间注释""我太忙了""项目耽误了"这些往往是不写注释的理由。所以,程序员们认为,最理想的解决方法是‘写代码前先写注释'。例如:

public void ProcessOrder()

{

// Make sure the products are available

// Check that the customer is valid

// Send the order to the store

// Generate bill

}

10. Write comments as if they were for you (in fact, they are)把代码的读者想象成你自己(实际情况往往如此)

注释代码时,不仅仅要为将来可能维护你代码的人考虑,而且要考虑到读注释的可能是你。伟大的Phil Haack说过:"每当有一行代码被敲上屏幕,你都要从维护的角度审视一遍这段代码。" "As soon as a line of code is laid on the screen, you're in maintenance mode on that piece of code."(著名的话不敢不附上原句)

结果,我们自己往往是我们良好注释的受益者,或者是烂注释的受害人。

11. Update comments when you update the code(更新代码时,记得更新注释)

如果不能随着代码的更新而更新注释,那么即使再准确的注释也毫无意义。代码和注释必须同步,否则这些注释对于维护你代码的程序人员来说简直是折磨。在使用refactoring工具自动更新代码时,应尤其注意,它们会自动更新代码而不会改变注释,这些注释自然就过期了。

 

12. The golden rule of comments: readable code(可读性良好的代码是最好的注释)

对于许多程序员来说,基本的原则之一就是:让代码自己说话。有人可能会怀疑这是那些不爱写注释的程序员的借口,然而这确实是一个不争的事实。自我解释良好的代码对于编码来说大有益处,不但代码容易理解甚至使注释变得没有必要。举例来说,在我的文章《Fluid Interfaces》中展示了什么是清晰的自我解释型代码:

Calculator calc = new Calculator();

calc.Set(0);

calc.Add(10);

calc.Multiply(2);

calc.Subtract(4);

Console.WriteLine( "Result: {0}", calc.Get() );

在本例中,注释是没必要的,并且会违背tip#4 。为了使代码更加可读,应该考虑使用适当的名字(像在经典的《Ottinger's Rules》描述的),确保正确的缩进和代码风格栏线(代码风格栏线是类似于#region #endregion这类的东西吧?)。如果这一点做的不好,直接后果是,你的注释看起来就像是在为晦涩难懂的代码而道歉。

13. Share these tips with your colleagues(与你的同事share这些tips)

尽管tip#10中曾说过良好的注释会是自己从中收益,但是这些tips会使所有开发人员收益,尤其是在团队合作的环境中。因此大方的与同事分享这些注释的技巧,让我们都能写出易懂而且好维护的代码。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Win11 Tips Sharing: Skip Microsoft Account Login with One Trick Win11 Tips Sharing: Skip Microsoft Account Login with One Trick Mar 27, 2024 pm 02:57 PM

Win11 Tips Sharing: One trick to skip Microsoft account login Windows 11 is the latest operating system launched by Microsoft, with a new design style and many practical functions. However, for some users, having to log in to their Microsoft account every time they boot up the system can be a bit annoying. If you are one of them, you might as well try the following tips, which will allow you to skip logging in with a Microsoft account and enter the desktop interface directly. First, we need to create a local account in the system to log in instead of a Microsoft account. The advantage of doing this is

How to use Copilot to generate code How to use Copilot to generate code Mar 23, 2024 am 10:41 AM

As a programmer, I get excited about tools that simplify the coding experience. With the help of artificial intelligence tools, we can generate demo code and make necessary modifications as per the requirement. The newly introduced Copilot tool in Visual Studio Code allows us to create AI-generated code with natural language chat interactions. By explaining functionality, we can better understand the meaning of existing code. How to use Copilot to generate code? To get started, we first need to get the latest PowerPlatformTools extension. To achieve this, you need to go to the extension page, search for "PowerPlatformTool" and click the Install button

A must-have for veterans: Tips and precautions for * and & in C language A must-have for veterans: Tips and precautions for * and & in C language Apr 04, 2024 am 08:21 AM

In C language, it represents a pointer, which stores the address of other variables; & represents the address operator, which returns the memory address of a variable. Tips for using pointers include defining pointers, dereferencing pointers, and ensuring that pointers point to valid addresses; tips for using address operators & include obtaining variable addresses, and returning the address of the first element of the array when obtaining the address of an array element. A practical example demonstrating the use of pointer and address operators to reverse a string.

What are the tips for novices to create forms? What are the tips for novices to create forms? Mar 21, 2024 am 09:11 AM

We often create and edit tables in excel, but as a novice who has just come into contact with the software, how to use excel to create tables is not as easy as it is for us. Below, we will conduct some drills on some steps of table creation that novices, that is, beginners, need to master. We hope it will be helpful to those in need. A sample form for beginners is shown below: Let’s see how to complete it! 1. There are two methods to create a new excel document. You can right-click the mouse on a blank location on the [Desktop] - [New] - [xls] file. You can also [Start]-[All Programs]-[Microsoft Office]-[Microsoft Excel 20**] 2. Double-click our new ex

VSCode Getting Started Guide: A must-read for beginners to quickly master usage skills! VSCode Getting Started Guide: A must-read for beginners to quickly master usage skills! Mar 26, 2024 am 08:21 AM

VSCode (Visual Studio Code) is an open source code editor developed by Microsoft. It has powerful functions and rich plug-in support, making it one of the preferred tools for developers. This article will provide an introductory guide for beginners to help them quickly master the skills of using VSCode. In this article, we will introduce how to install VSCode, basic editing operations, shortcut keys, plug-in installation, etc., and provide readers with specific code examples. 1. Install VSCode first, we need

Create and run Linux ".a" files Create and run Linux ".a" files Mar 20, 2024 pm 04:46 PM

Working with files in the Linux operating system requires the use of various commands and techniques that enable developers to efficiently create and execute files, code, programs, scripts, and other things. In the Linux environment, files with the extension ".a" have great importance as static libraries. These libraries play an important role in software development, allowing developers to efficiently manage and share common functionality across multiple programs. For effective software development in a Linux environment, it is crucial to understand how to create and run ".a" files. This article will introduce how to comprehensively install and configure the Linux ".a" file. Let's explore the definition, purpose, structure, and methods of creating and executing the Linux ".a" file. What is L

Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Tsinghua University and Zhipu AI open source GLM-4: launching a new revolution in natural language processing Jun 12, 2024 pm 08:38 PM

Since the launch of ChatGLM-6B on March 14, 2023, the GLM series models have received widespread attention and recognition. Especially after ChatGLM3-6B was open sourced, developers are full of expectations for the fourth-generation model launched by Zhipu AI. This expectation has finally been fully satisfied with the release of GLM-4-9B. The birth of GLM-4-9B In order to give small models (10B and below) more powerful capabilities, the GLM technical team launched this new fourth-generation GLM series open source model: GLM-4-9B after nearly half a year of exploration. This model greatly compresses the model size while ensuring accuracy, and has faster inference speed and higher efficiency. The GLM technical team’s exploration has not

PHP programming skills: How to jump to the web page within 3 seconds PHP programming skills: How to jump to the web page within 3 seconds Mar 24, 2024 am 09:18 AM

Title: PHP Programming Tips: How to Jump to a Web Page within 3 Seconds In web development, we often encounter situations where we need to automatically jump to another page within a certain period of time. This article will introduce how to use PHP to implement programming techniques to jump to a page within 3 seconds, and provide specific code examples. First of all, the basic principle of page jump is realized through the Location field in the HTTP response header. By setting this field, the browser can automatically jump to the specified page. Below is a simple example demonstrating how to use P

See all articles