Code neat Way (ii) the way of elegant annotation

Source: Internet
Author: User

First, best practice

Comments should declare the high-level intent of the code, not the obvious details

Counter Example

Description

The above method is used to generate signatures based on parameters, and the implementation steps of the signature algorithm are described in detail in the comments, which is an overly descriptive detail of the code.

Positive example

Summarize

1. Comments must be outside the code to express something, the code can contain content, note must not appear

2. If it is necessary to comment, please comment on the intent (why), instead of commenting on the implementation (how), everyone will see the code

Use global annotations at the file/class level to explain how all parts work

Positive example

Summarize

Typically, each file or class should have a global comment outlining the role of the class

Public APIs need comments, other code uses caution

Counter Example

Description

The above interface provides the Dubbo RPC service as a public API, provided to the caller in a two-party package, although the code is simply missing basic information such as the interface profile and the method annotations.

Positive example

Summarize

Public APIs must have comments, class files using class annotations, public interface methods with method annotations

Illustrate with carefully selected input and output examples in annotations

Positive example

Summarize

Examples of input and output for common methods, especially common tool class methods, are often more powerful than any other language.

Note Be sure to describe the code closest to it

Counter Example

Description

The method has a line of code that deletes a data from the map, and the comment is placed before the put call, not directly before the remove

Positive example

Summarize

Note to place the closest location to its description code

Note Be sure to correspond to the code

Counter Example

Description

Note that the length of the generated random string cannot exceed 16 characters, the actual code has been modified to 32 characters, and the comments here will have misleading side effects

Positive example

Summarize

1. Comments must correspond to the code, usually the code changes corresponding to the comments will also change

2. If you do not need to use annotations carefully, note the same as the code needs maintenance updates

Be sure to annotate the constants

Counter Example

Positive example

Summarize

Add a valid comment to each constant

Skillfully used markers (todo,fixme,hack)

1. TODO has unfinished matters

2. Fixme code has a known issue to fix

3. HACK indicates that the code has HACK logic

Example

Configuration tags

You can extend the configuration of the IDE to modify the tags, such as adding a resolution, associated defects and other information, with idea as an example to modify the entry as follows:

Summarize

1. Skillfully use Todo, fixme, hack and other annotations to identify the code

2. Timely processing of all identification code, avoid misuse

Add alert annotations as appropriate

Positive example

Description

This method creates an array linked list with a fixed size of 1 and a type map, which is rather odd and requires a comment explaining why

Summarize

There are some very hack logic in the code, and the changes can cause a higher risk, which needs to be annotated at this point.

Commented-Out Code

Counter Example

Description

Common routines, in order to facilitate the need to re-reuse the discarded code, directly commented out.

Positive example

Ditto, delete the comment section code

Summarize

Do not keep any commented-out code in the code, the version management software such as git can do things do not put in the code

Rules-style annotations

Counter Example

Description

Analyzing the above code can find two notes very awkward and superfluous:

1. Class annotations Use the default template, filled with invalid information

2. The IDE generates a large number of invalid annotations for getter and setter methods

Positive example

Summarize

1. Do not keep any routine comments, such as the IDE automatically generated redundant annotations

2. Do not generate any such comments, you can configure the IDE to achieve this effect, we recommend the use of Ling Fox plug-in

Log comments

Counter Example

Description

Modify existing code A lot of people will manually add comments explaining the date of modification, modification of the person and the description of the changes, the information is mostly redundant

Positive example

Code above, delete the comment

Summarize

Do not include the code in the Code of the book information, version management can do things do not do in the code

"Cane Notes"

Counter Example

Description

The sample code simply implements the ability to update the specified map k-v, if the target map does not exist, initializes a map with the specified k-v and returns with the method named Updateconfigwithspecifiedkv, which describes the implementation logic of the method in order to illustrate the full intent of the method.

Positive example

Summarize

Abandon "Cane Notes", don't give a bad name a comment, a good name is more important than a good comment

Overly-HTML annotations

Counter Example

Description

Class annotations Use a large number of HTML tags to describe, the actual effect does not bring benefits but increase the difficulty of reading

Positive example

Summarize

1. Common business Annotations Use HTML tags carefully, it will not give you a noticeable benefit, will only increase the reading difficulty

2. If it is a public API and is used to generate Javadoc, consider adding the necessary HTML tags, such as links, anchor points, etc.

Second, programming language annotation Practice

Java

File/Class Comment specification

Now the IDE installs the Ling Fox automatically configures the IDE's file templates to the following format:

It is strongly recommended to use the above configuration, unified, concise is the best. If you have special needs, you can refer to the custom class annotations:

Method Comment

The IDE provides a unified approach to annotation templates without manual configuration, and good method comments should include the following:

1. Description of the method, focusing on what the method is used to do, it is necessary to add an example of input and output

2. Parameter description

3. Return value Description

4. Description of the exception

As an example:

Block comments and Line comments

1. Single-line code comments using lines comments//

2. Multi-line code comments using block comments/* *

Python

File comments

Key description of the role of the file and how to use it

Class Comment

1. The class should have a document string that describes the class under its definition

2. Class public properties should be described

function comment

1. Args: Lists the names of each parameter, and uses a colon and a space after the name to separate the description of the parameter. If the description is too long than a single line of 80 characters, use a hanging indent of 2 or 4 spaces (consistent with other parts of the file). The description should include the desired type and meaning. If a function accepts *foo (variable-length argument list) or **bar (any keyword argument), the *foo and **bar should be listed in detail.

2. Returns: Describes the type and semantics of the return value. If the function returns none, this part can be omitted

3. Raises: List all exceptions related to the interface

Multi-line comments and end-of-line comments

1. Complex operation Multi-line Comment description

2. The more obscure code uses the end of line comment

Golang

Line Comment

Common annotation Style

Package annotations

/**/is typically used for package annotations, providing the corresponding information for this package as a whole, each package should contain a doc.go to describe its information.

Javascript

Common/**/and//, usage is basically the same as Java.

Shell

Only # is supported, each file contains a top-level comment that describes the copyright and summary information.

Other

Ready to be perfected

Summary

This article summarizes the best practice scenarios for annotations in programming and illustrates the examples, and then provides some explanatory templates and practice tips related to the specification in different programming languages. About comments My personal knowledge is: Comments that are code, comments that are documents, write good notes one of the necessary qualities of an engineer, in neat code premise, less annotation is the pursuit of high. Notes on the practice of the temporary write here, the following will continue to improve, but also welcome you to provide good tips, the code is mostly from the daily business projects, but also part of the open Source Library, if there is something wrong please correct me.

The author of this article: Zhu Jian

Read the original

This article is the original content of the cloud-Habitat community and cannot be reproduced without permission.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.