The purpose of code annotation and formatting is to make the code easier to read and understand, and improve the maintainability of the Code, below are 10 best practices (especially Java) about code comments and formats ).
Code comment
Annotation is a part of the code. It is very important to include the annotation in the statistical code line. A piece of code without any comments may be completely useless. Despite some extreme suggestions that the Code should have self-Annotated methods, we recommend that you annotate the necessary conditions for good code.
- Write comments only when necessary
- Do not write comments for each line of code, which is useless and reduces readability, for example:
- Int count = 0; // set the initial value for the count variable, which everyone can understand (?!?)
- Lack of annotations increases the difficulty and practice of code maintenance. First, the variables and method names should be understandable and self-Annotated. Below are two bad examples:
- Int s = sqrt (v1) + v2/v3 + fread (s). getChar (0 )//(?!?)
- List <int> getVal (int val, int len, String op )//(?!?)
Do not write incorrect comments, which is worse than no comments.
Write comments for very important variables instead of using self-document styles
It is required to write comments for all public methods and interfaces.
You should delete some useless content in the document, such as todo.
Code formatting
Many development tools provide code formatting functions, such as maven checkstyle. These formatting operations can be performed automatically when the code is saved, however, the formatting rules of these tools are different from the requirements of each company. Therefore, before use, you should set the rules to be consistent with the company code format specifications.
Below are some suggestions for code formatting:
- Use brackets in a uniform way: You can use parentheses in the same line or change a new line. This does not matter. The key is to be consistent.
- Uniform Rules for empty rows. For example, three empty rows can be created after the method is completed, and whether or not each line of code is separated by blank lines or not. These lines should be implemented according to their own habits, but should be unified.
- Uniform indent Handling Methods
- The number of characters in each line should be limited to improve code readability. Generally, about 80 characters are the most suitable
- The spaces in the Code must be consistent. For example:
- Operators and variables:
- Between the statement and the brackets:
- If (value) {, public class {
- In the loop:
- For (int I = 0; I <length; I ++)
- Type conversion:
- (Int) value, (String) value
Original English, OSCHINA Original translation