Code writing specification (Java)

zhaozj2021-02-16  50

A Java code to write out a few days ago!

Code writing specification

First, the purpose

For code, the primary requirement is that it must be correct and can run in accordance with the real thoughts of the programmer; the second requirement is that the code must be clear and easy to understand, so that other programmers can easily understand the actual work of the code. In the field of software engineering, the origin of the source program is marked with maintenanceability, readability, an important part of the software project. And there is currently no coding style documentation, so that many times, the programmer does not have a common standard, which can be followed, the coding style is different, the program is maintenanceability, and readability is also very poor. By establishing code writing specification, forming development team coding conventions, improving program reliability, readability, modification, maintainability, inheritability, and consistency, guarantee the quality of program code, inheriting software development results, full Use resources to make the developers' work results can be shared.

Based on the existing coding style of the industry, this paper describes a JBuilder-based project style, strive for a unified programming style, from the overall coding style, code file style, function writing style, variable style, annotation style, etc. Several aspects are elaborated. (These norms are not necessarily abolished, but must have a good readability)

Second, the overall coding style

1, indent

The indentation is recommended in 4 spaces. It is recommended to set the block IDent of the Editor page in Tools / Editor Options to 4, Tab Size is 8. Pretreatment statements, global data, title, additional instructions, function description, label, etc. are written. The "{", "}" pair alignment of the statement block, and is aligned with the previous row, the statement of the statement block classes is recommended for each "{", "}" separately, which is easy to match. The default mode in JBuilder is the beginning "{" is not a single line, it is recommended to change into the above format (set in the Project / Default Project Properties Setting Code STYle Select Braces to NEXT LINE).

2, space

In principle, the variables, classes, constant data, and functions are aligned in their type, and the modified name is aligned. Keyword principles, such as: if (...), etc.. The space for the operator is as follows: "::", "->", "[", "]", " ", "-", "~", "!", " ", "-" (Specific Negative Negative Number), "&" and other operators are not vacuum (where the single operator is connected to the operand), other operators (including most budget operators and The three-mean operator "?:" The two sides plus a space, and it can be aligned in the case when the function is defined, but it can be not available when the function is implemented. "," The operator is only in it. The grid is required to be empty or more spaces. Whether there is parentheses, the annotation of the comment after the statement is applied to the statement, and the statement is aligned as much as possible. Individuals believe that this item can be followed or not.

3, alignment

In principle, the relationship is closely related to the alignment, including type, modification, name, parameter, etc. are aligned. The length of each row should not exceed too much screen. If necessary, the wrap is appropriate, when the wrap is as possible, "," or operator, it is best to take the operator after the wrap, and the following lines are in the first line of this statement. Injunction, but the statement is still subject to the indentation of the first line, that is, the next line is "{" should be aligned with the first line. The variable definition is preferably aligned by adding spaces, and the same type of variable is preferably placed together. As shown in the following example: int value; int result; intlene; Object CurrenTry;

Personally think that this item can be followed or not in accordance with personal habits.

4, blank line

There is no rule-free space, such as 10 consecutive spaces. Two rows between the sections of the program file structure, if it is not necessary, it can only be empty, each function is generally empty. Since each function must have a function explanation, it is usually only empty or not empty. However, there should be at least a row for the case where there is no function description. For your own functions, it is recommended to share "// ------". The function internal data and the code should be at least one line, and the code should be spaced in the code. It is recommended to have a variable declaration in the code in the code. At least four "P" in the class, there is also a space between the data and the function therein.

5, note

Comments are the specific embodiment of software readability. The program annotation amount generally accounts for 20% of the program encoding, and the software engineering requirements are not less than 20%. Program comments cannot be used in abstract languages, similar to "processing", "loop" computer abstract language, to accurately express the procedure's processing instructions. For example: "Calculate Net Demand", "calculate the processing of the first step", etc. ". Avoid using comments per line programs, you can add a period of annotation in front of a program to have a clear processing logic.

Note is essential, but should not be too much, do not write annotations for write comments. The following is four essential notes: A. Title, additional instructions.

B. Description of functions, class, etc. For almost every function, there should be an appropriate description, usually before the function implementation, before the function implementation part, the content is mainly the function, purpose, algorithm, etc. of the function, the parameter description , Return value description, etc., there must be some instructions such as special hardware and software requirements if necessary. Common functions, publications of public classes must be made by annotation, and design ideas, of course, choose the appropriate naming format to help you explain more clearly.

C. There must be some instructions in the code that does not clearly or inlet.

D. and a small amount of other comments, such as the annotation of custom variables, code writing time, etc.

Note There is two kinds of bidders and line bets, which refers to: "/ ** /" and "//" recommendation to a block annotation, D line notes, B, and C depend on the situation, but should be unified, At least Class B annotation in one unit should be unified. Specific pairs of different documents, structural annotations will be described in detail later.

6, code length

For each function, it is recommended to control the length of about 53 rows as much as possible, and the code for more than 53 rows should be reconsider to split it into two or more functions. The function split rules should not undermine the original algorithm, and the part of the split should be reused. For repetitive code to be used in multiple modules or forms, it can be independently become a function with public nature, placed in a common module.

7, page wide

Page width should be set to 80 characters. Sourcecodes generally do not exceed this width and cause the unable to display, but this setting can also be flexible. In any case, the long statement should be folded after a comma or a operator. One statement fold It should shrink 2 characters more than the original statement.

8, number of lines

In a general integrated programming environment, each screen can only display a program that does not exceed 50 rows, so this function is about 5-6 screen display, and if you have 8 on some environments, you can display it. In this way, whether it is a reader or a modification process, it will be difficult. It is therefore recommended to extract the block of completing the comparison independent function, and become a function separately. Take the block that completes the same or similar functions, independently is a child function. It can be found that the more the functions of the upper layer are, the more sub-function, the more the product is completed, the more the base is completed. This is a sign of a good program. This way, we can easily control the logic of the entire program in a lower function, and focus on the implementation of a certain aspect in the underlying function. Third, code file style

All Java (*. Java) files must comply with the following style rules:

File generation

For specifications of Java derived classes, try to generate file formats with JBuilder's Object Gallery tools to avoid manual header files / implement files. Package / import

Package Row To be used in the IMPORT, the standard package name is before the local package name and in the alphabetical order. If the IMPORT line contains different subdirectory in the same package, you should use * to process.

Package hotlava.net.stats;

Import java.io. *; import java.util.observable; import hotlava.util.Application; here Java.IO. * is used instead of InputStream and OutputStream.

File head comment

The header of the file is mainly indicative of some information of the file, which is an overall description of the program that enhances the readability and maintainability of the program. The file header is generally after the Package / Imports statement, the class description. Require at least the file name, creator, create time, and content description. In the code generated by the JBuilder Object Gallery tool, you will add a comment in the class, the project file, and we also add some comments, and its format should be as constrained as follows:

/ ** * title: Determine the mouse position class * Description: Determine which job field in which the mouse is currently in the job number * @copyright: Copyright (c) 2002 * @company: hit * @Author: rivershan * @version: 1.0 * @Time: 2002.10.30 * /. Class

Next, the annotation of the class is generally used to interpret the class.

/ ** * a class representing a set of packet and byte counters * it is observable to allow it to be watch Extends and Implements

Public Class Counterset Extends Observable Implements Cloneable

.CLASS FIELDS

Next is a member variable of class:

/ ** * packet counter * / protected int [] packets; member variables for publicoco must generate a document (JavaDoc). Member variables defined by Proceted, Private and Package If the name meaning is clear, you can not comment.

The access method is next to the access to the class variable. It is just simple to get values ​​to assign values ​​to the class variable, you can simply write on one line. (Individual thinks as much as possible) / ** * get the counters * @return an array containing The statistical data. This array ha modified by the caller. * / Public int [] getpackets () {Return CopyArray (Packets, Offset);

Public int [] getBytes () {return copyArray (bytes, offset);

Public int [] getpackets () {return packets;}

Public void setpackets (int [] packets) {this.packets = packets;} Other methods don't write on one line

. Constructor

Next is a constructor, it should be written in an incremental manner (such as: writing more).

Access Type ("Public", "Private", etc.) and any "static", "firm" or "synchronized" should be written in one line, and the methods and parameters can be written separately, which makes the method and parameters easier to read.

PubliccounterSet (int size) {this.size = size;}

Cloning method If this class can be cloned, then the next step is Clone method:

Publicobject Clone () {Try {counter = (counter) super.clone (); obj.packets = (int []) packets.clone (); obj.size = size; return} catch (clonenotsuportedException E) { Throw new interfacerror ("UNEXPECTED ClonyNotSupportedException:" E.getMessage ());}}

Class method

The method of writing classes below:

/ ** * set the packet counters * (Such as When Restoring from a database) * / protected finalvoid setArray (int [] R1, int [] R2, int [] R3, int [] R4) throws illegalgumentException {// / / Ensure the arrays area of ​​equal size // if (r1.length! = R2.Length || r1.length! = R3.Length || r1.length! = R4.length) throw new illegalargumentException ("Arrays Must Be "); System.ArrayCopy (R1, 0, R3, 0, R1.LENGTH); System.ArrayCopy (R2, 0, R4, 0, R1.LENGTH);}

Tostring method

In any case, every class should define the toString method:

PUBLICSTRING TOSTRING () {string retval = "counter"; for (int i = 0; i

If the main (String []) method is defined, it should be written at the bottom of the class.

Fourth, function writing style

Named of function.

Typically, the function's naming is also principle based on the action meaning of the expression function, usually made by the verb head, and then keeps the noun indicating the action object, and the first letters of each word should be capitalized. In addition, there are some common rules naming. If you take the get, you will use the get head, then keep the name of the object you want; set the number of sets, then you can follow the name of the object you want; For the ON head, then the name of the corresponding message; the function of active action can be named DO head, and then the corresponding action name. Similar rules have a lot, you need programmers to learn more outstanding programs, gradually accumulating experience, in order to make a good function name.

Function notes

The system automatically generates functions, such as mouse action response functions, etc., there is no need for too much annotation and explanation;

For a function written, if the system key function, you must indicate the information of the function above the function implementation section, the format is as follows:

/ *** Function Name: * Editor: * Reference: * Features: * Enter parameters: * Output parameters: * Note: * /

I hope to follow the above format as much as possible.

V. Symbol style

. total requirements

For the definition of various symbols, there is a common point, that is, the abbreviation of English words or English words should be used. Do not use simple but meaningless strings, do not use the Arab figures as much as possible, but also use Chinese Pinyin The first letter. Such name is not advocated: Value1, Value2, Value3, Value4 ....

For example: File (file), code (number), data, pagepoint, Faxcode, Address, Bank, ...

Variable name

a. Variable name prefix

Variable type prefix example INTEGER INT INTCOUNTBYTE BYTMOVESHORT SHTRESULTLONG LNG LNGTOTALFLOAT FLT FLTAVERAGED DBL DBLTOLERANGCEBOOLAN BLN SILDATA CHR Chrinput Array Arr Arrdata

Variable names generally have a certain expression, and the first letter of each word in the variable name is capitalized (removed from the first word)

b. Descriptive variable name and process name:

The main body of the variable name or process name uses the case in cases and to describe its purpose as much as possible, and the other process name should start with the verb, such as initNameArray, CloseDialog

The agreement of the object name:

The prefix of the object name:

Object Type Prefix Button BTNCANVAS CVSCHECKBOX CHKIMAGE IMGLABEL LBLONT LSTCHOICE CHCDIALOG DLGEVENT EVTFRAME FRMMENU MENUPANEL PNLTextArea TxatextField TXF. Package Name

The name of Package should be composed of a lowercase word.

Class named

The name of the class must consist of one or several uppercase or abbreviations that can express the meaning of the meaning of the meaning of the class and other letters, which make this Class's name easier to understand.

. Class variable name

The name of the variable must be started with a lowercase letter. The latter words begin with uppercase letters. For a member variable of the class, add the prefix M_ of the Member (member) when naming its identifier. For example, an identifier is m_dwflag, it represents a variable that is a type of two-word, which represents a flag.

. Static Final variable name

The name of the Static Final variable should be capitalized and point out the full meaning.

Name of parameters.

The name of the parameter must be consistent with the naming specification of the variable.

. Array name

Arrays should always be named in the following ways: byte [] buffer; rather than: byte buffer [];

The parameters of the method use meaningful parameters, if possible, use the same name as the field to assign value:

SetCounter (int size) {this.size = size;}

Mysterious number

The first thing to say is a mysterious number. We often use some quantities in the program, it has a specific meaning. For example, now we write a salary statistics, 50 employees, we will use 50 this number in the program to make a variety of calculations. Here, 50 is "mysterious number". Why call it mystery? Because other programmers see 50 this number in the program, I don't know its meaning, I can only guess.

"Mysterious number" in the program will reduce the readability of the program and should try to avoid it. Avoiding the method to define the mysterious number as a constant. Note that this constant should be able to express the meaning of the number and should be all override to distinguish from the identifier corresponding to the variable. For example, the number above 50, we can define a constant named NumofemPloyees instead. This way, other programmers can be easily understood when they read the program.

转载请注明原文地址:https://www.9cbs.com/read-26678.html

New Post(0)