Java development coding specification

xiaoxiao2021-03-06  30

Java development coding specification

http://www.yourblog.org/data/20046/90260.html

2 Java Development Coding Specification 2.1 Preface This coding specification summarizes the desirables of the various Java coding specifications currently found, and has developed the norms that should be observed when new Jiuqi system development. From the contents of various coding specifications, it mainly includes naming specifications (including classes, variables, methods, etc.), document annotation specification, coding format specification, and some programming practices. It is more important to standard naming and document comments, and they are very helpful to improve software, especially JDK contains the javadoc tool for extracting document comments, and the standardized document comment can be directly extracted into documents for subsequent modification maintenance. Personnel Reference, its content is more accurately detailed than the update is not enough design document. The encoding format and programming conventions also have an impact on program readability, but it is necessary to completely comply with certain difficulties, and the encoding format can be unified after the format specification tool is completed after the encoding is completed. Therefore, the following about naming specifications and document comments specification requires developers to strictly abide by, and the coding format specification and programming practice are recommended to comply with the developers. The preparation of this specification mainly refers to the Java coding specification on the Sun website (http://java.sun.com/doc.doc.doc.html) and Java program coding specification on the IBM website. 2.2 Naming Specification 2.2.1 Java Language Program Element Named Identifier Type Name Rules Example Pack (Packages) A ​​unique package prefix is ​​always lower-write ASCII letters and is a top domain name, usually COM, EDU, GOV, MIL, NET, ORG, or English double-character code specified by ISO 3166 standard in 1981. The subsequent part of the package is not the same as the naming specification within the respective mechanisms. Such naming specifications may distinguish between departments, projects, or registration names in a specific directory name. The com.cattsoft.bss.customer class is a word, using the case where the case is mixed, the first letter of each word is capitalized. Try to make your class name simple and description. Use intact words to avoid abbreviations (unless the abbreviation is more widely used, like url, html) class customer; class bankaccount; interface (interfaces) case-sensitive rules are similar to class INTERFACE RASTERDELEGATE; Interface Storing; method (Methods) method The name is a verb, which uses cases of cases mixed, the first letter of the first word, the first letter of the following words. Run (); Runfast (); getBackground (); variable (variables) In addition to the variable name, all instances, including classes, types, usual, using case-write mix, the first letter of the first letter, after the word The initial letters. The variable name should not begin with the scribe or dollar symbol, although this is allowed in grammar. The variable name should be short and described. The selection of the variable name should be easy to remember, that is, it can be pointed out. Try to avoid a variable name of a single character unless it is a disposable temporary variable. Temporary variables are usually named I, J, K, M and N, which are generally used for integer; C, D, E, which are generally used for characters.

CHAR C; INT i; FLOAT MYWIDTH; instance variable (instance variables) case, in addition to the number of variable names, in addition to a downline int _employeid; string _name; Customer _CUSTOMER; constant (constants), a statement, and ANSI constants, should All uppercase, interlaced interlaced in words. (Try to avoid ANSI constants, easy to cause errors) Static Final Int min_width = 4; static final int max_width = 999; Static Final INT GET_THE_CPU = 1; parameter (parameters) The name and variable of the parameters parameter consistent. Arrays arrays should always name them: byte [] buffer; instead of: byte buffer []; Figure 2 1 Java language program element Name 2.2.2 Enterprise Bean Name Although enterprise bean is also a Java program, However, because it consists of multiple parts, it is specifically designed for it: [Note: DD indicates that the project is an item in the deployment descriptor file] Project Name Rules An example of enterprise bean name (DD) EJB Accountejb EJB Archive File JAR Name (DD) JAR Accountjar Enterprise Bean Main Class Name> Bean AccountBean Home Interface Name Home AccountHome Remote Interface Name Name> Account Local Home Interface Name Local HOME LocalacCountHome Local interface named Local Localaccount Abstract Data Mode Name (DD) Account Chart 2 2 Enterprise Bean Name 2.2.3 Program file Naming In addition to JSP, all programs in this system are "." Java "is a complicated class file, which also follows the naming specification for class names. The naming rules for the JSP file also follow the naming specifications for the class name. The same is a Java program, which is also divided into different types depending on its use. In this system, there is an Action Form Bean, Action, Action, Action Servlet, DAO, SessionBean, etc. Since the type has been distinguished in the catalog structure of the package, it is not distinguished in the name of the file. It is recommended that the system uses the following directory structure: Chart 2 3 Recommended Directory Structure of this system 2.3 Document Note Specification Java programs There are two types of annotations: Implementation Comments and Document Comments. Realization comments are those defined using "/*...*/" and "//". Document Note (called "DOC Comments") is a unique java and is defined by "/**...*/". Document comments can be converted to an HTML file through the Javadoc tool, and the entire JDK document is generated by the JavadoC tool. Realize comments to comment code or implement detail. Document Note describes the code from the perspective of the IMPLEMentation-Free. It can be read by those developers who have no source code. Note Should be used to give a summary of the code and provide additional information provided by code itself. Note Should only include information related to the reading and understanding procedures. For example, information such as how the corresponding packet is established or in which directory should not be included in the comment. In the comment, it is possible to explain the important or not obvious place in design decisions, but it should be avoided. Excessive annotations are easy to obsolete.

It is usually avoided that the code updates may be more comments. Comments should not be written in the big boxes drawn in an asterisk or other character. Note Should not include special characters such as patriant characters and backfall. 2.3.1 Implementation Comment Formats programs can have four things that implement annotations: Block, single-line, tail, and end-of-line. 2.3.1.1 Block Comments block annotations are often used to provide descriptions for files, methods, data structures, and algorithms. Block comments are placed at the beginning of each file and before each method. They can also be used elsewhere, such as internal interior. Block note inside features and methods should have the same indentation format with the code they described. The first block of comments should have an empty line, which is used to split block annotations and code, such as: / * * here is a block comment. * / 2.3.1.2 Single-line Comments short comments can be displayed In one line, and the following code has the same indented level. If a note cannot be written within one line, it will be used (see "Block Comment"). There should be an empty line before a single line comment. The following is an example of a single-line annotation in a Java code: if (condition) {/ * handle the condition. * / ...} 2.3.1.3 Tail Note (TRALING COMMENTS) is very short comment to be located with the code they want to describe In the same line, there should be sufficient blank to separate the code and comments. If there is a plurality of short comments appear in large segment code, they should have the same indentation. The following is an example of the tail end annotation in a Java code: if (a == 2) {return true; / * special case * /} else {return isprime (a); / * Works Only for odd a * /} 2.3.1.4 End-of-line comments comment default "//", you can comment out part of the row or a line. It is generally not used for annotation text; however, it can be used to comment out of the continuous multi-line code segment. The following is an example of all three styles: if (foo> 1) {// do a double-flip. ...} else {return false; // evlain why here.} // if (bar> 1) {/ / // // DO a triple-flip. // ... //} // else {// Return false; //} 2.3.2 Document Note Document Note Description Java class, interface, construct Method, method, and field (field). Each document comment will be placed in the comment delimiter / **...*/, a comment corresponds to a class, interface or member. This comment should be in the declaration: / ** * the example example {... In the development of this system, the developer is required to make the developer's method for each class and the proplic, protected To make a document comment. The contents of the class document annotation require the following order: (

and are HTML tags, used for typography, meaning for another.

) / ** * Class Description: The main function of this class is explained *

Author: writers Code *

Version: The current version of the program *

revision of history : The content of the program's modification history is recorded * / to the document annotation requirements of the method and its order: (where @ param, @ return, and @Exception are common tags in the javadoc tool, separately Parameters, return values, and exceptions, when there are multiple parameters, return values, and exceptions, these tags can be used in multiple lines. There are still many other functions in Javadoc, because it is not used here, no more Description.) / ** * Function Description: The main function of the method will be described * @Param Parameter Name Parameter Description * @RETURN Return Value Description * @Exception Extraordinary Name Description * / Review format of the annotation described here, see "See" See " Java Source File Example. The development tools used by this project have good support for Javadoc, which can automatically prompt the document tags after typing @, and can easily generate documents in the graphical interface without the command line. 2.4 Coding Format Specification 2.4.1 File Organization A file is divided by a paragraph that is splitted and identifies an optional annotation of each paragraph. More than 2,000 rows of procedures are difficult to read and should be avoided as much as possible. "Java Source File Example" provides a reasonable Java program example. 2.4.1.1 Java Source Files Each Java source file contains a single public class or interface. If private and interfaces are associated with a public class, they can put them and public classes in the same source file. The public category must be the first class or interface in this file. The Java source file also follows the following rules: Header Notes and Introduction Statements Class and Interface Declaration 2.4.1.1.1 Beginning Comments All source files should have a C language style annotation, where the name is listed , Version information, date, and copyright statement. This section is repeated with the above document comments, follow the document comments. 2.4.1.1.2 Package and Import Statements (Package and Import Statements) In most Java source files, the first non-note line is a packet statement. You can follow the introduction statement after it. For example: package java.awt; import java.awt.peer.canvaspeer; 2.4.1.1.3 Class and Interface Declarative (Class and Interface Declaration) The following table describes the various parts of the class and interface declarations and the presence thereof. See "Java Source File Example" An example of a comment. Particular / Interface Declaration of Part 1 / Interface Document Note (/ ** ... * /) This annotation is included in this comment, see "Document Notes" 2 or Interface Declaration 3 / Interface Implementation (/ * ... * /) If necessary, the comment should contain any information about the entire class or interface, and this information is not suitable as a class / interface document comment. The 4 types of (static) variables are firstcoming the common variables of the class, followed by the protection variable, and then the package level variable (no access modifier, access modifier), and finally the private variable. 5 instance variables are first common, followed by the protection level, and then the package level (no access to the modifier), and finally the private level. 6 Structure 7 Methods These methods should be packet according to functions, rather than scope or access. For example, a private class method can be placed between two public instance methods. Its purpose is to make it easier to read and understand the code.

Figure 2 Class 2 and interface declarations of each part of the Interface declaration and the presence of them 2.4.2 Indentation 4 spaces are often used as a unit of indentation. The exact interpretation of indentation is not specified in detail. A tab is equal to 8 spacers (rather than 4). 2.4.2.1 Line Length To avoid exceeding 80 characters in length, because many terminals and tools cannot be well processed. Note: The examples used in the document should use a shorter chance, and the length is generally not more than 70 characters. 2.4.2.2 Wraping Lines When an expression cannot accommodate in one line, it can be disconnected according to the following general rules: After a comma is disconnected in front of an operator, there is a high level (Higher-Level) Disconnect, not a lower level (Lower-Level) to disconnect the new line of the same level in the same level, if the above rules have caused your code to confuse or make your code piles in the right Then, it is ingenuity to indent the 8 spaces. The following are some examples of call disconnection method: someMethod (longExpression1, longExpression2, longExpression3, longExpression4, longExpression5); var = someMethod1 (longExpression1, (longExpression2, longExpression3) someMethod2); The following are examples of two disconnected arithmetic expression. The former is better because the disconnect is located outside the bracket expression, which is a higher level of disconnection. longName1 = longName2 * (longName3 longName4 - longName5) 4 * longname6; // PREFFER longName1 = longName2 * (longName3 longName4 - longName5) 4 * longname6; // AVOID Following are two examples of indenting method declarations. The former is a conventional situation. The latter will move the second line and the third row very right, so the generation is taken to indent the 8 space // conventional indentation SomeMethod (int Anarg, Object Anotherarg, String YetanothereRG, Object) andStillAnother) {...} // INDENT 8 sPACES tO AVOID VERY DEEP INDENTS private static synchronized horkingLongMethodName (int anArg, Object anotherArg, String yetAnotherArg, Object andStillAnother) {...} wrap if statements generally used 8-space rule Because conventional indentation (4 spaces) will make the statement look more difficult.

For example: // Don't Use this indentation if (condition1 && condition2) || (Condition3 && condition4) ||! (Condition5 && condition6)) {// bad wsomethingAboutit (); // make this line easy to miss } // use this indeadation @| (condition3 && condition4) ||! (Condition5 && condition6)) {dosomethingAboutit ();} // or use thisif ((condition1 && condition2) || (Condition3 && Condition4) {DOSMETHINGABOUTIT ();} There are three feasible methods for processing three-yuan arithmetic expression: alpha = (alongbooleaneXpression)? Beta: gamma; alpha = (AlongBooleaneXpression) Beta: gamma; alpha = (AlongBooleaneXpression)? Beta: Gamma; 2.4.3 Declaration 2.4.3.1 Number Per line of each line (Number Per line) Recommend a row of declarations, as this is conducive to writing comments. That is, int level; // indeentation level int size; // size of table is better than, int level, size; do not put declaration of different types of variables in the same line, for example: int foo, fooarray []; // Wrong! Note: A space is placed between the type and the identifier, and the other alternative is the use of tab: int level; // indeentation level int size; // size of table Object currententry; // currently successd Table Entry 2.4.3.2 Initialization is initialized while declaring local variables. The only reason not to do this is that the initial value of the variable depends on some previous calculations. 2.4.3.3 Placement Declares the variables only at the beginning of the code block. (A block refers to any code that is included in the middle of braces "{" and "}".) Do not declare when the variable is used for the first time. This will make the programs that are not concentrated, and the transplantability of the code is hindered in this scope.

Void mymethod () {int = 0; // beginning of method block if (cond) {int rt2 = 0; // beginning of "if" block ...}} This rule is an index variable of the FOR loop For (int i = 0; i

For example: return; return mydisk.size (); RETURN (size? Size: defaultsize); 2.4.4.4 IF, IF-ELSE, IF ELSE-IF ELSE statement (IF, IF-ELSE, IF ELSE-IF ELSE STATEments) IF -ELSE statement should have the following format: if (condition) {statements;}} {statements;}}} {statements;} else {statements;} else {statements;} else {statements; } Note: The IF statement is always enclosed in "{" and "}" to avoid using the following format: if (condition) // avoid! This omits the braces {}! Statement; 2.4.4.5 for statement ( For Statements) A FOR statement should have the following format: for (Initialization; Condition; Update) {statements;} A empty FOR statement (all work is initialized, conditional judgment, update clauses) should have the following format: for (Initialization; Update); When using a comma in the initialization of the for statement or in the update clause, avoid the use of three or more variables, resulting in improvement. If necessary, use a separate statement before the FOR cycle (for the initialization subsis) or the FOR cycle (for the update clause). 2.4.4.6 While Statements A While statement should have the following format while (condition) {statements;} A empty While statement should have the following format: While (condition); 2.4.4.7 Do-While statement (Do-while Statements) A Do-While statement should have the following format: do {statements;} while (condition); switch statements) A Switch statement should have the following format: Switch (CASE ABC: Statements; / * Falls through * / case def: statements; break; case xyz: statements; break; default: statements; break;} Whenever a case is executed in down (because there is no BREAK statement), the location of the Break statement should usually be in the BREAK statement add notes. In the sample code above, comments / * falls through * /.

2.4.4.9 try-catch statements A try-catch statement should have the following format: Try {statements;} catch (ExceptionClass E) {statements;} A tryally statement is also followed by a FINALLY statement, Regardless of whether the TRY code block is successfully implemented, it will be executed. Try {statements;} catch (ExceptionClass e) {statements;} finally {statements;} 2.4.5 blank (blank line) blank spacer separates logic related code segments to improve Readability. The following cases should always use two spaces: two sections of a source file, class declarations, and interface declarations, the following conditions should always use an empty line: local variables within the method between two methods. And between the first statement of the method, between the block comments or the two logic segments within one method, to improve readability 2.4.5.2 spaces below should use spaces: - a follow-up The keywords in parentheses should be separated by spaces, for example: while {...} Note: Space should not be placed between the method name and its left brackets. This will help distinguish between keywords and method calls. - Blank should be in the back of the comma in the parameter list - all binary operators, except ".", You should use spaces to separate from the operand. One dollar operator and operand should not be added, such as: negative ("-"), self-increasing (" ") and self-reduction ("-"). For example: A = C D; A = (A B) / (C * D); while (D = S ) {n ;} printsize ("size is" foo "/ n"); - for The expression in the statement should be separated by a space, for example: for (expr1; expr2; expr3) - Forced transformation, you should follow a space, for example: mymethod, (ibject) x); MyMethod ((int) (INT) CP 5) ((int) (I 3)) 1); 2.5 Programming Practities 2.5.1 Provides access control for examples and class variables (PROVIDING Access to Instance and Class Variables) is not enough Reasons, do not declare examples or class variables as public. Typically, instance variables do not require explicit settings (SET) and gotten, which is usually produced as the edge effect of method calls (Side Effect). A proper example of a public instance variable is that the class is only the data structure, no behavior. That is, if you want to use a structure rather than a class (if the Java supports the structure), then the instance variable declaration of the class is suitable. 2.5.2 Reference Class Variables and Class Methods (Referring to Class Variables and Methods) Avoid accessing a class of static variables and methods with an object. You should be replaced by a class name.

For example: classMethod (); // ok aclass.classMethod (); // ok anobject.classMethod (); // Avoid! 2.5.3 Constants is located in the FOR cycle as a numeric constant of the counter value, except -1, 0 and 1, should not be written directly to code. 2.5.4 Variable Assignments Avoid assigning the same value to multiple variables in one statement. It is hard to read. For example: foobar.fchar = barfoo.lchar = 'c'; // Avoid! Do not use the assignment operator to be confused with the equivalent relationship operator. For example: IF (C = D ) {// Avoid! (Java Disallows) ...} should be written into IF ((C = D )! = 0) {...} Do not use embedded to assignment operators attempt Increase the efficiency of the runtime, which is the work of the compiler. For example: D = (a = b c) r; // avoid! Should be written as a = B C; D = A R; 2.5.5 Other Formula 2.5.5.1 Parentheses (PARENTHESES) In terms of using parentheses in an expression containing a variety of operators to avoid operator priority issues, it is a good way. Even if the priority of the operator may be clear, it is not necessary for others. You can't assume that other programmers are as clear as you know the priority of the operator. IF (a == B && C == D) // Avoid! IF ((a == b) && (c == d)) // Right 2.5.5.2 Return Values ​​Try to make your program structure Combine. For example: if (booleaneXpression) {return true;} Else {Return false;} should be in the following method: Return BooleaneXpression; Similarly: if (condition) {returnix x;} return y; should write: Return (Condition? X: Y); 2.5.5.3 Conditional Operator "?" Expressions Before '?' in the conditional operator "If an expression containing binary operators appears in terms of three yuan operator?:" Before "?", Then a pair of parentheses should be added to the expression. For example: (x> = 0)? X: -x; Special Comments uses XXX in the comment to identify some unprecedented (BOGUS) but work (Works). Use fixme to identify some fake and error content. 2.6 Code Examples 2.6.1 Java Source File Examples The following example shows how to reasonably layout a Java source program containing a single public class. The layout of the interface is similar. See "Class and Interface Declaration" and "Text Refidence".

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

New Post(0)