Advanced specification of JAVA programming format, java programming

Source: Internet
Author: User

Advanced specification of JAVA programming format, java programming

A developer must have strict code specifications. For this reason, I have summarized some code specification cases.

Contents

1. Preface

2. Trial Scope

3. JAVA Naming rules --

3.1 Public conventions

3.2 Java files and packages

3.3 Class and interface naming rules

3.4 naming rules for methods

3.5 Constants

3.6 variables and parameters

3.7 components/Parts

3.8 set

3.9 mysterious number

3.10 others

3.11 Java exception

3.12 array naming

3.13 naming rules for database tables

3.14 database Field naming rules

3.15 JSP file name

3.16 Servlet Class Name

4. Writing format specifications

4.1 indent

4.2 Spaces

4.3 alignment

4.4 blank lines

4.5 annotations

5. Code File Style

 

1. Preface in order to ensure the readability of the system source program and enhance the maintainability of the system, the following programming specifications are formulated to regulate the programming of all parts of the system. The source program in other resources inherited by the system should also be modified in accordance with this specification. 2. Trial scope this document will serve as the programming format specification developed by Hebei Post Application System Software (JAVA language. Strict compliance with system coding, testing, and maintenance requirements. 3. JAVA Naming Convention 3.1 Public naming conventions refer to the naming of source file names, methods, directories, packages, database table names, database fields, and so on in the system. The names used by the system are expressed by abbreviations. The naming method is: prefix + {abbreviation}. The prefix indicates the purpose of the naming, such as database tables. The prefix is determined by the project team. All objects except public maintenance objects are named in lower case. One method is to use "_" as the connector, and the other is to connect the first letter of the phoneme directly in uppercase. In this specification, the first method is used for the database name and database field name, and the second method is used for the rest. You can accurately describe the complete English descriptors of variables, fields, classes, interfaces, packages, and so on. For example, if you use a name such as firstName, listAllUsers, or CorporateCustomer, you are not allowed to use Chinese pinyin or irrelevant words. Although Java supports Unicode naming, however, this specification prohibits the use of uppercase and lowercase characters for names of packages, classes, interfaces, methods, variables, fields, and so on to improve the readability of names. Generally, lowercase letters are used, but the first letter of the class and interface names and the first letter of any intermediate word should be capitalized. All package names are in lower case. If you want to use them as few abbreviations as possible, you must use them. For example, implement can be abbreviated to impl and manager can be abbreviated to mgr, for more information, see the table below. Misuse of abbreviations is prohibited. Avoid using long names (preferably up to 25 letters ).

Avoid using numbers, but use 2 instead of to, and use 4 instead of for, for example, go2Jsp.

3.2 When a Java file or package file name is strictly the same as its class, the first letter of all words is capitalized. A package name is generally named after a project or module. It is abbreviated and long and must be in lower case. Basic Package: com. czpost. All packages and files belong to this package. The package name is composed of the following rules: [Basic Package]. [Project name]. [Module name]. [submodule name]... for example: com. czpost. eims com. hepost. eims. the class cannot be directly defined under the basic package. All the classes and interfaces in the project must be defined in their respective project and module packages.

3.3 Class and interface naming rules the first letter of all words is capitalized. Use words that accurately reflect the class, interface meaning, and functions. Generally, nouns are used. The interface can contain an I prefix or a suffix such as able, available, and er.

3.4 The full English descriptor should be used for naming the standard method, and the combination of uppercase and lowercase should be used: the first letter of all intermediate words should be capitalized. The first word of the legal name often uses a verb with a strong action color. The value class uses the get prefix, and the value class uses the set prefix to determine whether the class uses the is (has) prefix. Example: Recommended sequence of getName () setSarry () isLogon () method parameters: (operator, Operation content, operation mark, and other parameters) Example: public void replace (String sourceStr, String oldStr, string newStr ){........}

3.5 constants Use complete uppercase English words and are connected with underscores (_) between words, for example, DEFAULT_VALUE.

3.6 we recommend that you use the Hungarian naming method for variables and parameter variables. For the terms, see "common conventions" integer variables (including int, short, and long): Start with n, for example: long nCredNum; float variables (including float and double): Start with f, for example, double fTranAmt; character variables: Start with c, for example, char cPageFlag; Date variables: Start with d, for example: date dToday; boolean variable: starts with is, for example: boolean isFlag; string variable: starts with s, for example: char sPageNo [2 + 1]; global variable: data Types that start with g, such as char gsBankNo [10 + 1]. Static variables: static variables are also global variables in the file, and naming rules are the same as global variables. System-level variables: system-level variables are also global variables and begin. For example, char _ sBankNo [10 + 1] does not have 'G '. Temporary variables are usually named I, j, k, m, and n. They are generally used for integer type; c, d, e, they are generally used for struct type.

3.7 components/components should adopt the complete English descriptor naming component (interface component) and follow the Hungarian naming rules such as btnOK and lblName. Button variable btn + Xxxxxxx For example: btnSave, btn Exit, btnPrint and other question variable lbl + Xxxxxxxx For example: lblName, lblSex and other object type prefixes Canvas cvs CheckBox chk Image img List lst Choice chc Dialog dlg Event evt Frame frm Menu menu Panel pnl TextArea txa TextField txf

3.8 a collection, such as arrays and vectors, should be named in the plural to indicate the object type stored in the queue. The full English descriptor should be used for naming. The first letter of all non-starting words in the name should be big-coded, And the prefix of the Set abbreviation should be used as appropriate. Example: Vector vProducts = new Vector (); // product Vector Array aryUsers = new Array (); // user list

3.9 The mysterious number Program often uses some quantities. It has specific meanings and defines the mysterious number as a constant. Note that the name of this constant should be able to express the meaning of this number, and should all be capitalized to distinguish it from the identifier corresponding to the variable. For example, 50 can be defined as a constant named NUM_OF_EMPLOYEES.

3.10 multiple numbers are used to represent multiple values. For example, orderItems.

3.11 The Java Exception class name is composed of words indicating the Exception type, such as ActionException. Abnormal instances generally use e, ex, and so on. When there are multiple exceptions, use the Exception name or the abbreviation plus E, Ex and so on, such as: SQLEx ActionEx

3.12 The array name array should always be named in the following way: byte [] buffer; not byte buffer [];

3.13 database table naming Rules use underscores (_) to separate the prefixes and names of elements. The name is composed of lowercase letters. If the named word is composed of a single word, it can be spelled out in full; if it is composed of multiple words, it can be abbreviated. Underlines are used between abbreviations. For example, database table: View starting with 't_': Index starting with 'v _ ': Index starting with't, unique index of database and table ending with '_ idx': starting with 't_' and ending with' _ uidx'

3.14 database Field naming rules a single word can be used in full spelling if it is a multi-word combination. Underlines are used between abbreviations. The name is composed of lowercase letters. No prefix.

3.15 JSP file naming uses a complete English description to describe the functions completed by JSP, including a vivid verb as much as possible, the first letter in lowercase, such as viewMessage. jsp, editUser. jsp or forumChooser. jsp.

3.16 Servlet class naming generally corresponds to the Service object and the suffix Service, such as UserService and TradeService.

4. Writing format specifications strictly require the writing format to make the program neat and beautiful, easy to read, unified style, programmers must have a clear understanding of the necessity of standardized writing. It is recommended that the source program be developed using the eclipse tool, and the format specifications should be set in advance in the tool.

4.1 indent it is recommended that four spaces be used as the unit. Pre-processing statements, global data, titles, additional descriptions, function descriptions, and labels are written in the top level. The "{", "}" pairs and alignment of the statement block with the previous line. We recommend that each "{", "}" occupies a single line for statement indentation of the statement block class, this facilitates matching. The default method in sclipse is "{", which is not a single row. We recommend that you change it to the preceding format.

4.2 space in principle, variables, classes, constant data, and functions are of the type, and spaces are appropriate between the modifier names, which are aligned as needed. If. The spaces of operators are as follows: ":", "->", "[", "]", "++ ","--","~ ","! "," + ","-"(Positive and negative signs)," & "(reference), and other operators do not have spaces on either side (where the single-object operator refers to the side connected to the operand ), other operators (including most binary operators and three-object operators "? : "Add a space on both sides. when defining a function, you can use multiple null or non-empty spaces for alignment. This is not required in function implementation. "," The operator only has one space after it. When alignment is required, it can be left blank or multiple spaces. Whether there are Parentheses or not, use spaces to separate the comments added after the statement line and align them as much as possible. I personally think that this item can be followed or not according to my habits.

4.3 alignment in principle, the closely related rows should be aligned. alignment includes type, modifier, name, parameter, and other alignment parts. In addition, the length of each line should not exceed the screen length. If necessary, wrap the line appropriately. when changing the line, try to place it at "," or operator. it is best to start with an operator after wrapping, and the following lines are indented at the first line of the statement, but the statement is still indented at the first line, that is, the next line is "{" should be aligned with the first line. It is best to add spaces or TAB keys for variable definitions to form alignment. It is best to put variables of the same type together. For example: int nValue; int nResult; int nLength;

4.4 empty rows do not have empty rows without rules, for example, 10 empty rows in a row. There is a blank line between the parts of the program file structure. Because each function requires a function description comment, only one or no blank line is required. However, at least one line should be blank if no function description is provided. We recommend that you add "// ------" to separate your own functions. There should be at least one line of data in the function and at least one line of code should be empty in the Code. We recommend that you leave a blank line before the variable declaration in the code. There must be at least one line between the four "p" in the class, and there should also be a blank line between the data and the function.

4.5 annotation is a concrete manifestation of software readability. Program comments generally account for 20% of program code, and the software engineering requirement is not less than 20%. Program annotations cannot use abstract languages. Computer abstract languages such as "processing" and "loop" must accurately express program processing instructions. Avoid comments for each program line. You can add comments before a program to have a clear processing logic. Comments are indispensable, but they should not be too many. Do not passively write comments for writing comments. There are four necessary Annotations: The title and additional descriptions. Description of functions and classes. Almost every function should be properly described. Generally, before function implementation, it is added to the function prototype without function implementation, its content mainly describes functions, purposes, algorithms, parameters, return values, and so on. If necessary, it also describes specific software and hardware requirements. Declarations of Public Functions and public classes must be annotated to describe their usage methods and design ideas. Of course, choosing the appropriate naming format can help you better understand things. It must be noted that the Code is not clear or cannot be transplanted. And a small number of other comments, such as the comments of custom variables and the code writing time.

5. code File style all Java (*. java) files must comply with the following style rules: file generation for standard JAVA Derived classes, use eclipse tools to generate file formats as much as possible, avoiding manual header files/implementation files. The package/import package line must be prior to the import line. The standard package names in the import must be prior to the local package name and sorted alphabetically. If the import line contains different subdirectories in the same package, use * for processing. Package hotlava.net. stats; import java. io. *; import java. util. Observable; import hotlava. util. Application; here java. io. * is used to replace InputStream and OutputStream. The file header annotation mainly indicates some information about the file. It is a general description of the program and can enhance the readability and maintainability of the program. The file header comment is generally placed after the package/imports statement and before the Class description. At least the file name, creator, Creation Time, and content description must be written. The format should be as follows:/*** Title: determines the mouse position class * Description: determines which job column the mouse is currently in and returns the job number * @ Copyright: Copyright (c) 2002 * @ Company:  * @ author: rivershan * @ version: 1.0 */Class is followed by Class annotations, which are generally used to interpret classes. /*** A class representing a set of packet and byte counters * It is observable to allow it to be watched, but only * reports changes when the current set is complete */next is the class definition, including extends and implements public Class CounterSet extends Observable implements Cloneable class Fields in different rows

 

 

Next is the class member variable:/*** Packet counters */protected int [] packets; The public member variable must generate the document (JavaDoc ). Member variables defined by proceted, private, and package can be uncommented if the name has a clear meaning. The next step is the method for accessing class variables. It is simply used to obtain the value of the variable value of the class, you can simply write it on a row. (I personally think that it should be written by branch whenever possible)

/*** Get the counters * @ return an array containing the statistical data. This array has been * freshly allocated and can be 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 should not be written in a row. The next step is the constructor. It should be written in an incremental manner (for example, a large number of parameters should be written later ). Access type ("public", "private", etc .) and any "static", "final" or "synchronized" should be in one row, and the method and parameter should be written in another row, so that the method and parameter can be easier to read.

Public CounterSet (int size ){

This. size = size;

}

Clone method if this class can be cloned, the next step is the clone method: public Object clone (){

Try {

CounterSet obj = (CounterSet) super. clone (); obj. packets = (int []) packets. clone (); obj. size = size; return obj;

} Catch (CloneNotSupportedException e ){

Throw new InternalError ("Unexpected CloneNotSUpportedException:" + e. getMessage ());

}

}

Class method:

/*** Set the packet counters * (such as when restoring from a database) */protected final void setArray (int [] r1, int [] r2, int [] r3, int [] r4) throws IllegalArgumentException {

/// Ensure the arrays are of equal size // if (r1.length! = R2.length | r1.length! = R3.length | r1.length! = R4.length) throw new IllegalArgumentException ("Arrays must be of the same size"; System. arraycopy (r1, 0, r3, 0, r1.length); System. arraycopy (r2, 0, r4, 0, r1.length);} The toString method should be defined for each class in any case:

 

public String toString() {   String retval = "CounterSet: "; for (int i = 0; i < data.length(); i++)      {        retval += data.bytes.toString();        retval += data.packets.toString();     }     return retval; } 

 

 


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


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.