Java Language Coding Specification (Java Code Conventions)

zhaozj2021-02-12  155

Java Language Coding Specification (Java Code Conventions)

1 Introduction 1.1 Why is the WHY Have Code Conventions Coding Standards for programmers, with the following reasons: - A software life cycle, 80% of the cost is maintenance - almost no Any software, in its entire life cycle, all maintained by the initial developers - coding specifications can improve software readability, allowing programmers to completely understand new code as soon as possible - if you put the source code as product release It is necessary to make sure that it is well packaged and clear, as you have built any other product to implement the specification, each software developer must consistently abide by the coding specification. everyone. 1.2 Acknowledgments This document reflects the coding standard part in Sun Microsystems, Java language norms. The main contributors include: Peter King, Patrick Naughton, Mike Demoney, Jonni Kanerva, Kathy Walrath, and Scott Hommel. This document is now maintained by Scott Hommel. For comments, please send to the SHOMMEL@eng.sun.com2 file name (file names) lists the commonly used file names and their suffixes. 2.1 File Suffixes Java Program Using the following File suffix: File Category File suffix Java source file. Java Java bytecode file. Class 2.2 Common file names Common file names include: file names Gnumakefile makefiles The preferred file name. We use Gnumake to create a (Build) software. ReadME Overview The preferred file name 3 file organization of the contents of the specific directory The file is set by the paragraph divided by the spacer and the 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. 3.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: - Start comments (see "Opening Note") - Packages and introduction statements (see "Package and Introduction Statements) - Class and Interface Declaration (see" Class and Interface Declaration ")

3.1.1

Beginning Comments All source files should have a C language-style annotation in the beginning, where the class name, version information, date, and copyright statement: / * * ClassName * * Version Information * * Date * * CopyRight NOTICE * / 3.1.2 Package and introduction statement (Package and Import Statements) In most Java source files, the first non-promised line is a packet statement. You can follow the introduction statement after it. For example: package java.awt; import java.awt.peer.canvaspeer; 3.1.3 Class and Interface Declaration The following table describes the various parts of the class and interface declarations and the order of them appear. 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. 4 Regeneration Typing (Indentation) 4 spaces are often used as a unit of indentation. The exact interpretation of indentation is not specified in detail (space VS. Table). A tab is equal to 8 spacers (rather than 4). 4.1 Line Length Try 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. 4.2 Wrapping Lines When an expression cannot be accommodated within a line, it can be disconnected according to the following general rules: - Disconnect behind a comma - disconnected in front of an operator - Ning better (Higher- The disconnection of Level, not a lower level (Lower-Level) - New line should be aligned with the beginning of the same level expression - If the above rules have caused your code to confuse or make your code The pile is squeezed on the right, then it will be indented in 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; 5 Note (Comments) Java program has two category of annotations: Implementation Comments and Document Comments.

Realizing comments are those who have seen in C , use /*...*/ and // definitions. Document Note (known as "DOC Comments") is a unique java and is defined by / the / **.... Document comments can be converted to an HTML file through 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. Note: Frequent comments sometimes reflect the low quality of the code. When you feel forced to add anything, consider rewriting the code clearer. 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. 5.1 Implementation Comment Formats Program can have four things that implement annotations: block, single-line, tail, and end-of-line. 5.1.1 Block Comments block comments 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 time should have a blank line, which is used to discrolize block annotations and code, such as: / * Here is a block comment. * / Block comment can begin with / * - so INDENT (1) The identification of the start of a code block without rearing it. / * - * Here is a block comment with some us want indent (1) to ignore. * * One * two * three * / Note: If you don't use Indenter, you don't have to be in the code. Use / * -, or may run indent (1) for others. See "Document Notes" 5.1.2 Single-line Comments short annotation can be displayed in one line and have the same indented level with the subsequent code. 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. * / ...} 5.1.3 TRALING Comments Magnual Note You can be located with the code you 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 * /} 5.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; //} 5.2 Document Note: Example of the annotation format described herein, see "Java Source File Example" If you want to know more, see "How to Write Doc Comments for Javadoc", which contains information about document comment tags (@return, @param, @see): http: //java.sun .com / javadoc / writedoccomments / index.html To learn more about document comments and javadoc, see Javadoc's Home: http://java.sun.com/javadoc/index.html Document Note Description Java class , Interfaces, constructors, methods, and fields (field). Each document comment will be placed in the comment delimiter / **...*/, a comment corresponds to a class, interface or member. This comment should be before: / *** * The example class provides ... * / public class example {... Note Top-Level The class and interface is not indent, and its members are indentation of. The first row (/ **) describing the document annotation of the classes and interfaces does not need to be indented; the subsequent document comments are indented in each row (align the asterisk). Members, including constructor, the first line of its document comments indent 4 grids, and then indent the 5 grid per line. If you want to give information about classes, interfaces, variables, or methods, and this information is not suitable for writing in the document, you can use the implementation block annotation (see 5.1.1) or tightly follow the separate note behind the declaration (see 5.1.2). For example, the details of a class implementation should be placed in a block annotation that keeps followed by the class declaration, not in the document comment. Document comments cannot be placed in a definition block of a method or constructor, since Java will associate the first declaration after the document comment is associated with it. 6 Declarations 6.1 The number of declared variables per line is recommended to a row, 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 Selected Table Entry 6.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. 6.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, do not declare the same variable name in the internal code block: int count; ... mymethod () {if (condition) {int count = 0; // Avoid! ...} ...} 6.4 and interface Class and Interface Declarations When writing classes and interfaces, you should follow the following format rules: - The left parentheses before the method name and its argument "(" Do not have spaces - left braces "{" in declaration statement The end - right braces "}" one line, aligned with the corresponding statement statement unless it is an empty statement, "}" should follow "{" Class Sample Extends Object {Ivar1; Int iVar2; Sample INT I, INT J; Ivar2 = I; Ivar2 = J;} INT EMPTYMETHOD () {} ...} - Method and Method Between 7.1 Page 7.1 Picture of SIMPLE STATEments At most, include a statement, such as: Argv ; // Correct Argc--; // Correct Argv ; argc--; // Avoid! 7.2 Composite Statements composite statement is the statement sequence included in braces, "{{语}". For example, the following sections are included in the statement to indent a hierarchy - left braces "{" should be at the end of the complex statement, ""} " One line should be aligned and aligned with the complex statement .- Brackets can be used for all statements, including a single statement, as long as these statements are part of the IF-ELSE or FOR control structure. This makes it easy to add a statement without worrying Bacrostep, introduced into bugs. 7.3 Return statements (RETURN Statements) A returnit statement with return values ​​does not use parentheses "()" unless they make the return value more apparent in some way.

For example: return; return mydisk.size (); RETURN (SIZE? SIZE: DEFAULTSIZE); 7.4 IF, IF-ELSE, IF ELSE-IF ELSE statement (IF, IF-ELSE, IF ELSE-IF ELSE STATEments) IF-ELSE The statement should have the following format: if (condition) {statements;} {statements;}} {statements;}} {statements;} else {statements; : The IF statement is always enclosed in "{" and "}" to avoid using the following format: if (condition) // avoid! This omits the braces {}! Statement; 7.5 for statement (for Statements) one The FOR statement should have the following format: for (Initialization; Condition; Update) {statements;} An empty FOR statement (all work is initialized, conditional judgment, updating clause) should have the following format: for (Initialization; Condition) Update; when using a comma in the initialization of the for statement or in the update clause, avoiding the use of three variables, resulting in increased complexity. If necessary, use a separate statement before the FOR cycle (for the initialization subsis) or the FOR cycle (for the update clause). 7.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); DO-WHILE STATEments) One Do -while statement should have the following format: do {statements;} while (condition); switch stat statement (Switch Statements) A Switch statement should have the following format: Switch (CASE ABC: Statements; / * Falls through * / casse DEF: Statements; Break; Case XYZ: Statements; Break; DEFAULT: Statements; Break;} Whenever a CASE is executed down (because there is no BREAK statement), a comment should usually be added at the location of the Break statement. In the sample code above, comments / * falls through * /. 7.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, no matter what TRY Whether the code block is successfully implemented, it will be executed.

Try {statements;} catch (exceptionclass e) {statements;} Finally {Statements; Blank Lines Separates logical code segments to improve readability. The following conditions should always use two space lines: - a source file between two sections - class declarations and interface declarations should always use an empty line: - Between two methods - method Between the first statements of local variables and methods - block comments (see "5.1.1") or single-line comments (see "5.1.2") - between two logic segments within a method, Increase readability 8.2 Spaces (Blank Spaces) should use spaces: - a keyword that follows parenthesis should be separated by spaces, for example: while (true) {...} Note: Space should not be placed in the method name There is between the 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. The one-dollar operator and the operand is not due to the splitter, such as: negative (" ") 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); 9 Naming Conventions Naming Specification makes the program easier to read, making it easier to understand. They can also provide information about identifier functions to help understand code, for example, whether it is a constant, package, or class. 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 1981 ISO 3166 Standard Specified English Double Character Code in the country. 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. Com.sun.engcom.apple.quicktime.v2edu.cmu.cs.bovik.chese class (Classes) Names Rules: Classified is a word, using case-by-case mixing, the first letter of each word. Try to make your class name simple and description.

Use intact words to avoid abbreviations (unless the abbreviation words are more widely used, like url, html) class rasser; Class ImageSprite; interface (interfaces) Naming rules: case-sensitive rules are similar to Interface RasterDelegate; interface storing; method Methods) method name is a verb, which uses cases of cases mixed, and the first letter of the first word is lowercase, the first letter of the 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; 10 Programming Formula 10.1 Provides access control for instances and class variables (providing Access to instance and class variables) Do not declare examples or class variables as public if there is not enough reason. 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. 10.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.classmeth (); // ok anobject.classMethod (); // Avoid! 10.3 Constant is located in the FOR cycle as a digital constant of the counter value, except -1,0 and 1 Other than, it should not be written directly. 10.4 Variable Assignments Avoid 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; 10.5 Other conventions (Miscellaneous Practices) 10.5.1 Parentheses (Parentheses) is generally The use of parentheses in an expression containing a variety of operators to avoid operator priority issues, it is a good method. 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 10.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); 10.5.3 Conditional Operators "?" Expressions Before '?' In The Conditional Operator) If an expression containing binary operators appears in a three-dimensional operator "?:" Before "?", Then a pair of parentheses should be added to the expression. For example: (x> = 0)? X: -x; 10.5.4 Special Comments uses XXX in the comment to identify some unprecedented (BOGUS) but work (Works) content. Use fixme to identify some fake and error content. 11 Code Examples 11.1 Java Source File Example The following example shows how to reasonably lay out a Java source program that contains a single public class. The layout of the interface is similar. See "Class and Interface Declaration" and "Text Refidence". / * * @ (#) Blah.java 1.8299 / 03/18

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

New Post(0)