Advanced specification of Java programming format
As a developer, we should have strict code specifications. To this end, I summarized some code specification cases.
catalogue
1. Preface
2. Trial scope
3. Java Naming specification--
3.1 public agreement
3.2 java files and packages
3.3 class and interface naming specification
3.4 method naming specification
3.5 constants
3.6 variables and parameters
3.7 components / parts
3.8 collection
3.9 mysterious numbers
3.10 others
3.11 Java exception
3.12 array naming
3.13 naming rules of database tables
3.14 naming rules of database fields
3.15 JSP file naming
3.16 servlet class naming
4. Standard writing format
4.1 indent
4.2 spaces
4.3 alignment
4.4 blank lines
4.5 notes
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 standardize the programming of each part of the system. The source programs in other resources inherited by the system shall also be modified accordingly according to this specification. 2. Trial scope this document will be used as Hebei post application system software Programming format specification developed by (Java language). It is required to be strictly followed in the process of system coding, testing and maintenance. 3. Java Naming specification 3.1 public agreement naming refers to the naming of source file name, method, directory, package, database table name, database field, etc. in the system. the naming used by the system is expressed by English abbreviations. the component of naming The formula is: prefix + {named morpheme abbreviation}, and the prefix expresses the purpose of naming, such as database table, etc. the naming prefix shall be determined by the project team. all objects except the public maintenance object of the system shall be named in lowercase. One way is to use "" As a connector, another way is that the first letter of morpheme is capitalized directly together. In this specification, the first method is adopted for database name and database field name, and the second method is adopted for others. use complete English descriptors that can accurately describe variables / fields / classes / interfaces / packages, etc. For example, if names like firstname, listallusers or corporatecustomer are used, it is strictly prohibited to use Chinese pinyin and irrelevant words. Although Java supports Unicode naming, this specification stipulates that packages, classes, interfaces, methods, variables, fields, etc. shall not be named in Chinese characters use case mixing to improve the readability of names. Generally, lowercase letters should be used, but the initials of class and interface names and the initials of any intermediate words should be capitalized. Package names are all lowercase. use abbreviations as little as possible, but if necessary, when using public abbreviations and customary abbreviations, such as implementation can be reduced to impl, manager can be reduced to Mgr, etc., refer to the following table for details, and abuse of abbreviations is strictly prohibited. avoid using long names (preferably no more than 25 letters).
Avoid using numbers, but use 2 instead of to, 4 instead of for, etc., such as go2jsp.
3.2 java file and package when the file name is strictly the same as its class, all words are capitalized. the package name is generally named after the project or module name, with less abbreviations and long names, all in lowercase. basic package: com Czpost, all packages and files belong to this package. The package name consists of the following rules: [basic package] [project name] [module name] [submodule name] For example: com czpost. eims com. hepost. eims. Until „ classes shall not be defined directly under the basic package. Classes, interfaces, etc. in all projects shall be defined in their respective project and module packages.
3.3 class and interface naming specification all words are capitalized. Use words that can accurately reflect the class, interface meaning, function, etc. Nouns are generally used. Interfaces can be prefixed with I or suffixes such as able, able, er, etc.
3.4 method naming standard method naming shall adopt complete English descriptors, mixed case: the first letter of all intermediate words shall be capitalized. The first word of a French name often uses a verb with strong action color. The value class uses the get prefix, the value setting class uses the set prefix, and the judgment class uses the is (has) prefix. Example: getname() setsarry() islogon() method parameter suggested order: (operator, operation content, operation flag, others...) example: public void replace (string sourcestr, string oldstr, string newstr) {........}
3.5 constants are capitalized words in complete English and underlined between words, such as default_ VALUE
3.6 Hungarian nomenclature is recommended for variables and parameter variables, For morpheme rules, see "public conventions" integer variables (including int, short, long): start with N, for example: long ncrednum; floating point variables (including float, double): start with F, for example: double ftranamt; character variable: start with C, for example: char cpageflag; date variable: start with D, for example: date dtoday; boolean variable: start with is, for example: Boolean isflag; character string variable: start with s, for example: char spageno [2 + 1] ; global variable: the type of combined data starting with G, for example: char gsbankno [10 + 1]; static variables: static variables are also global variables in the file, and the naming rules are the same as global variables. system level variables: system level variables are also global variables, with '' The type of combined data at the beginning. For example: char_ Sbankno [10 + 1] does not have 'g'. Temporary variables are usually named I, J, K, m and N, which are generally used for integers; c. D, e, they are generally used for character type.
3.7 components / parts shall be named with complete English descriptors (interface parts) and follow Hungarian naming rules, such as: btnok, lblname. button variables BTN + XXXXXX, such as: btnsave, BTN exit, btnprint, etc. subject variables LBL + XXXXXXX, such as: lblname, lblsex, etc. object type prefix canvas CVs Check@R_452_2419 @ chk Image img List lst Choice chc Dialog dlg Event evt Frame frm Menu menu Panel pnl TextArea txa TextField txf
3.8 set a set, such as array and vector, shall be named in plural to represent the object type stored in the queue. Complete English descriptors shall be used for naming. The first letter of all non beginning words in the name shall be capitalized, and the set abbreviation prefix shall be used appropriately. For example: vector vproducts = new vector()// Product vector array aryusers = new array()// User list
3.9 some quantities are often used in the mysterious number program. It has a specific meaning and defines the mysterious number as a constant. Note that the name of this constant should express the meaning of the number and should be capitalized to distinguish it from the identifier corresponding to the variable. For example, the number 50 can be defined as a number named num_ OF_ Instead of the constant of employees.
3.10 plural numbers shall be used for other designations. They represent multiple values. For example: OrderItems.
3.11 the Java exception class name consists of words and exceptions representing the exception type, such as actionexception. Exception instances generally use e, ex, etc. in case of multiple exceptions, use the exception name or abbreviation plus e, ex, etc., such as sqlex, actionex, etc
3.12 array naming arrays should always be named in the following way: byte [] buffer; Instead of byte buffer [];
3.13 naming rules for database tables prefixes and noun elements are separated by underscores. naming consists of lowercase letters. if the life noun is composed of a single word, it can be spelled in full; If it is multi word, use abbreviations. Underline between abbreviations. For example: library table: take "t _" view at the beginning: start with 'V' Beginning library table index: with't ' Start with '_ End with 'IDX' unique index of library table: with't ' Start with '_ End of uidx '
3.14 naming rules of database fields if the noun element is composed of a single word, it can be spelled in full; If it is multi word, use abbreviations. Underline between abbreviations. naming consists of lowercase letters. no prefix.
3.15 JSP file naming adopts complete English description to describe the functions completed by JSP, including a vivid verb as far as possible, with the first letter in lowercase, such as viewmessage jsp、editUser. JSP or forumchooser JSP, etc.
3.16 servlet class naming generally corresponds to the object served with the suffix service, such as userservice, tradeservice, etc.
4. The writing format is strictly required. The writing format is to make the program neat and beautiful, easy to read and unified style. Programmers should have a clear understanding of the necessity of standardized writing. It is recommended that the source program be developed using eclipse tool, and the format specification is set in the tool in advance.
4.1 indent it is recommended to indent in 4 spaces. Preprocessing statements, global data, titles, additional descriptions, function descriptions, labels, etc. are all written in the top grid. The "{" and "}" of the statement block are paired and aligned with the previous line. The statement indentation of the statement block class suggests that each "{" and "}" occupy a separate line for easy matching. The default method in Sclipse is that "{" at the beginning is not a single line. It is recommended to change to the above format.
4.2 spaces in principle, variables, classes, constants, data and functions should be properly spaced between their types and modified names and aligned as appropriate. A space above the keyword principle, such as: if (...) Wait. The spaces of operators are specified as follows: ":", "- >", "[", "]", "+ +", "--", "~", "!" "+"、 "-" (positive and negative sign), "&" (Reference) and other operators do not add a space on both sides (the unary operator refers to the side connected with the operand), and other operators (including most binocular operators and ternary operators "?:" add a space on both sides. When defining a function, it can also be aligned with multiple spaces or no spaces according to the situation, but it can not be used in function implementation. "," The operator is only followed by one space, and can not be empty or multiple spaces when alignment is required. Whether or not there are parentheses, the comments added after the statement line shall be separated from the statement with appropriate spaces and aligned as far as possible. I think this item can be followed according to personal habits.
4.3 alignment in principle, closely related lines should be aligned, including type, modification, name, parameter and other parts. In addition, the length of each line should not exceed too much of the screen. If necessary, wrap the line appropriately. When wrapping, it should be at "," or operator as far as possible. After wrapping, it is best to start with operator, and the following lines are indented by the first line of the statement, but the indentation of the first line of the statement still prevails, That is, the next line "{" should be aligned with the first line. Variable definitions are best aligned by adding spaces or tab keys, and variables of the same type are best placed together. The following examples are as follows: int nvalue; int nresult; int Nlength;
4.4 there shall be no irregular blank lines, such as ten consecutive blank lines. There is a blank line between each part of the program file structure. Since each function also has a function description note, it is usually only required to be blank or not, but at least one more line should be blank if there is no function description. It is recommended to add "/ / -------" to separate the functions written by yourself. At least one line should be left blank between the internal data of the function and the code, and the appropriate place in the code should be left blank. It is recommended to leave a blank line before the variable declaration in the code. There should be at least one empty line between the four "P" in the class, and between the data and the function.
4.5 notes are the concrete embodiment of software readability. The amount of program comments generally accounts for 20% of the amount of program coding, and the software engineering requirements shall not be less than 20%. Program annotation cannot use abstract language. Computer abstract languages such as "processing" and "loop" should accurately express the processing description of the program. Avoid using comments for each line of program. You can add a comment in front of a program with clear processing logic. Notes are essential, but they should not be too much. Don't write notes passively for the purpose of writing notes. The following are four necessary notes: title and additional description. description of functions, classes, etc. There should be appropriate descriptions for almost every function, usually before the function implementation, or before the function prototype if there is no function implementation part. Its contents mainly include the description of the function, purpose, algorithm, parameter description, return value description, etc. if necessary, there should also be some descriptions such as special software and hardware requirements. The declaration of public functions and public classes must be annotated to explain their use methods and design ideas. Of course, choosing an appropriate naming format can help you explain things more clearly. there must be a certain description where the code is unclear or not portable. and a small amount of other comments, such as comments on user-defined variables, code writing time, etc.
5. Code file style all Java (*. Java) files must comply with the following style rules: file generation. For standard Java derived classes, try to use eclipse tools to generate the file format, and avoid using hand-made header files / implementation files. the package / import package line should precede the import line, and the standard package name in import should precede the local package name in alphabetical order. If the import line contains different subdirectories in the same package, it should be handled with *. package hotlava. net. stats; import java. io.*; import java. util. Observable; import hotlava. util. Application; Here is Java io.* Use instead of InputStream and OutputStream. file header comments file header comments mainly indicate some information of the file and are the general description of the program, which can enhance the readability and maintainability of the program. File header comments are usually located after the package / imports statement and before the class description. It is required to write at least the file name, creator, creation time and content description. The format should be constrained as follows as far as possible: / * * Title: determine the mouse position class * Description: determine which job field the mouse is currently in and return the job number * @ Copyright: Copyright (c) 2002 * @ company: hit * @ Author: rivershan * @ version: 1.0 * / class. Next, the comments of the class are generally used to explain the class. / * ** 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 extensions and implements in different lines. Public class counterset extensions observable implements Cloneable class fields
Next is the member variable of the class: / * * packet counters * / protected int [] packets; The member variable of public must generate a document (Javadoc). If the name of the member variable defined by processed, private and package is clear, there can be no comments. The access method is followed by the access method of class variables. It is simply used to assign values to class variables to obtain values, which can be simply written on one line. (personally, try to write in separate lines)
/** *Get the counters * @return an array containing the statistical data. This array has been * freshly allocated and can be modified by the caller. */
Other methods should not be written on one line. The constructor is followed by the constructor. It should be written incrementally (for example, those with many parameters should be written later). Access types ("public", "private", etc.) And any "static", "final" or "synchronized" should be on one line, and the methods and parameters should be written on another line, so that the methods and parameters can be more readable.
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: write the method of the class below:
/** *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,r3,r1.length); System. arraycopy(r2,r4,r1.length); } toString method in any case, each class should define a toString method:
Main method if the main (string []) method has been defined, it should be written at the bottom of the class.