Java coding specification (2)-General Linux technology-Linux programming and kernel information. For details, see the following section. 6.3 Placement)
Declare variables only at the beginning of the code block. (A block refers to any code contained in braces "{" and .) Do not declare the variable when it is used for the first time. This will confuse unfocused programmers and impede code portability in this scope.
Void myMethod (){
Int int1 = 0; // beginning of method block
If (condition ){
Int int2 = 0; // beginning of "if" block
...
}
}
An exception to this rule is the index variable of the for loop.
For (int I = 0; I <maxLoops; I ++ ){...}
Avoid declaring local variables to overwrite the variables declared at the upper level. 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 Class and Interface Declarations)
When writing classes and interfaces, follow the following format rules:
-Do not have spaces between the left brackets before the method name and its parameter list.
-The left braces "{" are at the end of the statement.
-The right braces "}" start another line and align with the corresponding statement. Unless it is an empty statement, "}" should be followed "{"
Class Sample extends Object {
Int ivar1;
Int ivar2;
Sample (int I, int j ){
Ivar1 = I;
Ivar2 = j;
}
Int emptyMethod (){}
...
}
-Separate methods with empty lines
7 Statement (Statements)
7.1 Simple Statements)
Each line contains at most one statement, for example:
A compound statement is a sequence of statements contained in braces, such as "{statement }". For example, the following sections.
-The statements included in the statement should be indented to one level than the compound statement.
-The left braces "{" should be at the end of the row where the composite statement starts. The right braces "}" should start a new row and be aligned with the first line of the composite statement.
-Braces can be used for all statements, including a single statement, as long as these statements are part of an if-else or for control structure. This makes it easy to add statements without worrying about introducing bugs due to missing brackets.
7.3 return Statement (return Statements)
A return statement with a return value does not use parentheses "()" unless they make the return value more explicit 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)
The if-else statement should have the following format:
If (condition ){
Statements;
}
If (condition ){
Statements;
} Else {
Statements;
}
If (condition ){
Statements;
} Else if (condition ){
Statements;
} Else {
Statements;
}
NOTE: if statements are always included in "{" and "}" to avoid the following format that may cause errors:
If (condition) // AVOID! This omits the braces {}!
Statement;
7.5 for statement (for Statements)
A for statement should have the following format:
For (initialization; condition; update ){
Statements;
}
An empty for statement (all work is being initialized, condition judgment, and updated in the clause) should be in the following format:
For (initialization; condition; update );
When a comma is used in the initialization or update clause of a for statement, the complexity is increased because more than three variables are used. If necessary, separate statements can be used before a for loop (initialization clause) or at the end of a for loop (update clause.
7.6 while Statement (while Statements)
A while statement should have the following format
While (condition ){
Statements;
}
An empty while statement should have the following format:
While (condition );
7.7 do-while statement (do-while Statements)
A do-while statement should have the following format:
Do {
Statements;
} While (condition );
7.8 switch Statements)
A switch statement should have the following format:
Switch (condition ){
Case ABC:
Statements;
/* Falls through */
Case DEF:
Statements;
Break;
Case XYZ:
Statements;
Break;
Default:
Statements;
Break;
}
When a case is executed down (because there is no break statement), comments should be added at the position of the break statement. The above sample code contains comments/* falls through */.
7.9 try-catch Statement (try-catch Statements)
A try-catch statement should have the following format:
Try {
Statements;
} Catch (ExceptionClass e ){
Statements;
}
A try-catch statement may be followed by a finally statement. It will be executed no matter whether the try code block is successfully executed.
Try {
Statements;
} Catch (ExceptionClass e ){
Statements;
} Finally {
Statements;
}
White Space)
8.1 Blank Lines)
Empty lines separate segments related to logic to improve readability.
Two empty rows should always be used in the following cases:
-Two sections of a source file
-Between class declaration and interface declaration
Always use a blank line in the following cases:
-Between Two Methods
-Between the local variable in the method and the first statement of the Method
-Block comments (see "5.1.1") or single line comments (see "5.1.2 ")
-Two Logical segments in a method to improve readability
8.2 Spaces (Blank Spaces)
Spaces should be used in the following cases:
-A keyword followed by parentheses should be separated by spaces, for example:
While (true ){
...
}
Note: spaces should not be placed between the method name and the left parenthesis. This will help distinguish between keywords and method calls.
-The blank space should be placed behind the comma in the parameter list
-All binary operators except "." should be separated by spaces from the operands. There is no space between the unary operator and the operand, for example, minus sign ("-"), auto-increment ("++"), and auto-subtraction ("--"). For example:
A + = c + d;
A = (a + B)/(c * d );
While (d ++ = s ++ ){
N ++;
}
PrintSize ("size is" + foo + "\ n ");
-The expressions in the for statement should be separated by spaces, for example:
For (expr1; expr2; expr3)
-A space should be followed after forced transformation, for example:
MyMethod (byte) aNum, (Object) x );
MyMethod (int) (cp + 5), (int) (I + 3) + 1 );
9. Naming Conventions)
Naming rules make the program easier to read and understand. They can also provide information about the identifier function to help you understand the code, for example, whether it is a constant, a package, or a class.
Example of an identifier type naming rule
Packages the prefix of a unique package name is always all lowercase ASCII letters and is a top-level domain name, usually com, edu, gov, mil, net, org, or the English dual-character code specified by the ISO 1981 standard in 3166. The subsequent parts of the package name vary according to the naming rules of different organizations. Such naming conventions may consist of specific directory names to differentiate departments, projects, machines, or login names ). Com. sun. engcom. apple. quicktime. v2edu. cmu. cs. bovik. cheese
Class naming rules: a class name is a combination of uppercase and lowercase letters. Try to make your class name concise and descriptive. Use a complete word to avoid acronyms (unless the acronym is more widely used, such as URL or HTML) class Raster; class ImageSprite;
Interface (Interfaces) Naming rules: the Case-sensitivity rules are similar to the Class Name interface RasterDelegate; interface Storing;
The method name is a verb. It is a combination of upper and lower cases. The first letter of the first word is lowercase, And the last letter of the last word is capitalized. Run (); runFast (); getBackground ();
Except for the variable name, all instances, including Class and Class constants, use case-insensitive mixing. The first letter of the first word is lowercase, And the last letter of the second word is capitalized. Variable names should not start with an underscore or dollar sign, although this is syntactically allowed. Variable names should be brief and descriptive. The selection of variable names should be easy to remember, that is, they can point out their purposes. Avoid the variable name of a single character unless it is a one-time temporary variable. 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. Char c; int I; float myWidth;
The Instance Variables are in the same case as the variable names. In addition to the preceding underline int _ employeeId; String _ name; Customer _ customer;
The declaration of Constants (Constants) and ANSI Constants should be in uppercase and words should be separated by underscores. (Avoid ANSI constants whenever possible, which may cause errors) static final int MIN_WIDTH = 4; static final int MAX_WIDTH = 999; static final int GET_THE_CPU = 1;
Programming Practices)
10.1 provide Access control for instances and Class Variables (Providing Access to Instance and Class Variables)
If there is no reason, do not declare the instance or class variable as public. Generally, instance variables do not need to be explicitly set or acquired (gotten), which is usually generated as side effect of method calls.
An appropriate example with public instance variables is that the class is only used as a data structure and has no behavior. That is, if you want to use a structure (struct) rather than a class (if java supports structure), it is appropriate to declare the instance variables of the class as public.
10.2 reference Class Variables and Methods (Referring to Class Variables and Methods)
Avoid using an object to access static variables and methods of a class. It should be replaced by a Class Name. For example:
ClassMethod (); // OK
AClass. classMethod (); // OK
AnObject. classMethod (); // AVOID!
10.3 Constants (Constants)
The numeric constant located in the for loop as the counter value, except for-and 1, should not be directly written into the code.
10.4 Variable assignment (Variable Assignments)
Avoid assigning the same value to multiple variables in a statement. It is hard to understand. For example:
FooBar. fChar = barFoo. lchar = 'C'; // AVOID!
Do not use the value assignment operator in areas that are easily confused with equality operators. For example:
If (c ++ = d ++) {// AVOID! (Java disallows)
...
}
It should be written
If (c ++ = d ++ )! = 0 ){
...
}
Do not use the embedded (embedded) assignment operator to improve runtime efficiency, which is the work of the compiler. For example:
D = (a = B + c) + r; // AVOID!
It should be written
A = B + c;
D = a + r;
10.5 other conventions (Miscellaneous Practices)
10.5.1 Parentheses (Parentheses)
Generally, it is a good method to use parentheses in expressions containing multiple operators to avoid operator priority problems. Even though the operator priority may be clear to you, it may not be so for others. You cannot assume that other programmers know the operator priority as you do.
If (a = B & c = d) // AVOID!
If (a = B) & (c = d) // RIGHT
10.5.2 return value (Returning Values)
Try to make your program structure fit your purpose. For example:
If (booleanExpression ){
Return true;
} Else {
Return false;
}
Replace the following method:
Return booleanExpression;
Similarly:
If (condition ){
Return x;
}
Return y;
It should be written as follows:
Return (condition? X: y );
10.5.3 condition operator "? "Before the expression (Expressions before '? 'In the Conditional Operator)
If an expression containing binary operators appears in the ternary operator "? "? "Before, you should add a pair of parentheses to the expression. For example:
(X> = 0 )? X:-x;
10.5.4 Special Comments)
In the annotation, XXX is used to identify some unimplemented but usable (works) content. Use FIXME to identify some false and incorrect content.
11 Code example)
11.1 Java Source File Example)
The following example shows how to reasonably deploy a Java source program containing a single public class. The interface layout is similar. For more information, see "class and interface declaration" and "document comment ".
/*
* @ (#) Blah. java 1.82 99/03/18
*
* Copyright (c) 1994-1999 Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, California, 94303, U. S..
* All rights reserved.
*
* This software is the confidential and proprietary information of Sun
* Microsystems, Inc. ("Confidential Information"). You shall not
* Disclose such Confidential Information and shall use it only in
* Accordance with the terms of the license agreement you entered
* With Sun.
*/
Package java. blah;
Import java. blah. blahdy. BlahBlah;
/**
* Class description goes here.
*
* @ Version 1.82 18 Mar 1999
* @ Author Firstname Lastname
*/
Public class Blah extends SomeClass {
/* A class implementation comment can go here .*/
/** ClassVar1 documentation comment */
Public static int classVar1;
/**
* ClassVar2 documentation comment that happens to be
* More than one line long
*/
Private static Object classVar2;
/** InstanceVar1 documentation comment */
Public Object instanceVar1;
/** InstanceVar2 documentation comment */
Protected int instanceVar2;
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.