Java language Encoding specification selection from HK

Source: Internet
Author: User
Tags date format empty expression final naming convention variables variable
Code | Specification 1 Introduction (Introduction)
1.1 Why should there be coding specifications
Coding specifications are particularly important for programmers for a number of reasons:

-80% of the cost of a software lifecycle is to maintain
-Almost no software, throughout its lifecycle, is maintained by the original developer
-Coding specifications can improve the readability of the software, allowing programmers to understand the new code as quickly and thoroughly as possible
-If you release the source code as a product, you need to be sure that it is well packaged and clear, as any other product you have built

In order to execute the specification, each software developer must comply with the coding specification.


1.2 Copyright Notice
This document reflects the code standard portion of the Java language Specification in Sun Microsystems. Key contributors include: Peter king,patrick naughton,mike Demoney,jonni kanerva,kathy Walrath and Scott Hommel.

This document is now maintained by Scott Hommel, please send the comments to shommel@eng.sun.com


2. File name
This section lists the commonly used file names and their suffixes.

2.1 File suffix
The Java program uses the following file suffixes

File category file suffix
Java source files. java
Java byte code file. Class

2.2 Common file names
The Java program uses the following file suffixes

File category file suffix
Java source files. java
Java byte code file. Class


3. Organization of documents
A file is composed of paragraphs separated by blank lines and optional annotations that identify each paragraph. More than 2000 lines of procedures are difficult to read and should be avoided as far as possible. The Java source example provides an example of a properly laid out Java program.

3.1jAVA Source Files
Each Java source file contains a single public class or interface. If private classes and interfaces are associated with a common class, they can be placed in the same source file as public classes. The public class must be the first class or interface in this file.

The Java source file also follows the following rules:

-Start comment (see "opening note")
-Package and introduction statements (see "Packages and introduction statements")
-Class and interface declarations (see "Classes and Interface Declarations")


3.1.1 Opening Comment
All source files should have a C-language-style annotation at the beginning, listing the class name, version information, date, and copyright notice:

/*
* Classname
*
* Version Information
*
* Date
*
* Copyright Notice
*/


3.1.2 Package and Introduction statement
In most Java source files, the first non comment row is a package statement. After it can be followed by the introduction of statements. For example:

Package java.awt;

Import Java.awt.peer.CanvasPeer;


3.1.3 Class and interface description
The following table describes the various parts of the class and interface declarations and the order in which they appear. See an example of a comment in the Java source file paradigm.

Annotations to parts of a class/interface declaration
1 class/Interface document annotation (/**......*/) The information you want to include in this note, see document comments
2 Declaration of class or interface
3 class/Interface implementation annotations (/*......*/) if necessary, the annotation should contain any information about the entire class or interface, which is not appropriate for a class/interface documentation comment.
The 4 class (static) variable is first a public variable of the class, followed by a protection variable, then a variable at the package level (no access modifier, access modifier), and finally a private variable.
5 instance variables are public-level, followed by the protection level, then the package level (no access modifiers), and finally the private level.
6 constructors
7 Methods These methods should be grouped by function, not scope or access rights. For example, a private class method can be placed between two public instance methods. The goal is to make it easier to read and understand code.


4. Indent typesetting
4 spaces are often used as a unit of indent typesetting. The exact interpretation of indentation is not specified in detail (Space vs. tab). A tab is equal to 8 spaces (not 4).

4.1 Line length
Try to avoid a line that is longer than 80 characters long because many terminals and tools are not well handled.

Note: the example used in a document should use a shorter length of the president, typically no more than 70 characters.


4.2 Line Change
When an expression cannot fit within a row, it can be broken by the following general rules:

-Disconnect after a comma
-Disconnect in front of an operator
-Prefer a higher-level (higher-level) fracture rather than a lower-level (lower-level) Disconnect
-The new line should be aligned with the beginning of the same level expression on the previous line
-If the above rules cause your code to clutter up or stack your code on the right side, indent 8 spaces instead.

Here are some examples of disconnecting method calls:

SomeMethod (LongExpression1, LongExpression2, LongExpression3,
LongExpression4, LONGEXPRESSION5);

var = someMethod1 (LongExpression1,
SOMEMETHOD2 (LongExpression2,
LongExpression3));
Here are two examples of broken arithmetic expressions. The former is better because the disconnect is outside the bracket expression, which is a higher level disconnect.


longName1 = longName2 * (LongName3 + longname4-longname5)
+ 4 * LONGNAME6; Preffer

longName1 = longName2 * (LongName3 + longName4
-LONGNAME5) + 4 * LONGNAME6; Avoid
The following is an example of two indentation method declarations. The former is a conventional case. The latter, if used in normal indentation, will move the second and third rows to the right, so instead indent 8 spaces


Conventional indentation
SomeMethod (int anarg, Object anotherarg, String Yetanotherarg,
Object andstillanother) {
...
}

INDENT 8 spaces to avoid VERY DEEP indents
private static synchronized horkinglongmethodname (int anarg,
Object Anotherarg, String Yetanotherarg,
Object andstillanother) {
...
}
The wrapping of an if statement usually uses a 8-space rule, because a regular indent (4 spaces) makes the statement body look more laborious. Like what:

DON ' T Use this indentation
if ((Condition1 && condition2)
|| (Condition3 && Condition4)
||! (Condition5 && Condition6)) {//bad Wraps
Dosomethingaboutit (); Make is easy to MISS
}

Use this indentation INSTEAD
if ((Condition1 && condition2)
|| (Condition3 && Condition4)
||! (Condition5 && Condition6)) {
Dosomethingaboutit ();
}

OR Use this
if ((condition1 && condition2) | | (Condition3 && Condition4)
||! (Condition5 && Condition6)) {
Dosomethingaboutit ();
}


Here are three possible ways to deal with ternary expressions:


Alpha = (alongbooleanexpression)? Beta:gamma;

Alpha = (alongbooleanexpression)? Beta
: Gamma;

Alpha = (alongbooleanexpression)
? Beta
: Gamma;

5. Note

Java programs have two types of annotations: implementation annotations (Implementation comments) and document annotations (documents comments). Implementation annotations are those that have been seen in C + +, using/*...*/and/or defined annotations. Document annotations (referred to as "Doc comments") are unique to Java and are defined by/**...*/. Document annotations can be converted to HTML files through the Javadoc tool.

Implement annotations to annotate code or implement details. Document annotations describe code specifications from the point of view of implementing Freedom (Implementation-free). It can be read by developers who do not have the source code on hand.

Comments should be used to give an overview of the code and provide additional information that the code itself does not provide. Comments should contain only information related to reading and understanding programs. For example, information such as how the corresponding package is built or in which directory should not be included in the comment.

In a note, it is possible to explain what is important or not obvious in a design decision, but avoid providing repetitive information that is clearly expressed in the code. Redundant annotations are easy to get out of date. You should usually avoid annotations that might be obsolete by code updates.

Note: Frequent annotations sometimes reflect the low quality of the code. When you feel compelled to add a comment, consider rewriting the code to make it clearer.

Comments should not be written in large boxes that are drawn with asterisks or other characters. Annotations should not include special characters such as tabs and fallback characters.

5.1 Format to implement annotations

Programs can have 4 styles of implementing annotations: block, single line (single-line), tail end (trailing), and end of Line (End-of-line).

5.1.1-Block Notes

Block annotations are typically used to provide descriptions of files, methods, data structures, and algorithms. Block annotations are placed at the beginning of each file and before each method. They can also be used elsewhere, such as within the method. Block annotations within features and methods should have the same indentation format as the code they describe.

There should be a blank line at the top of the block annotation to separate the block annotation from the code, such as:

/*
* Here's a block comment.
*/
A block annotation can begin with a/*-so that indent (1) can recognize it as the beginning of a block of code and not rearrange it.

/*-
* Here are a block comment with some very special
* Formatting I want indent (1) to ignore.
*
* One
* Two
* Three
*/
Note: If you do not use indent (1), you do not have to use/*-in your code, or make concessions for other people who may be running indent (1) on your code.

See document comments

5.1.2 Single-line Comment

Short notes can be displayed on one line and have the same indentation level as the following code. If a comment cannot be written within a single line, you should use a block annotation (see "Block annotations"). There should be a blank line before a single-line comment. The following is an example of a single-line comment in a Java code:


if (condition) {

* * Handle the condition. */
...
}


5.1.3 end note
Very short annotations can be on the same line as the code they are describing, but there should be enough white space to separate the code and the comment. If you have multiple short annotations appearing in large code, they should have the same indentation.

The following is an example of a tail-end annotation in Java code:

if (a = = 2) {
return TRUE; /* Special Case * *
} else {
Return IsPrime (a); * Works is for odd a * *
}


5.1.4 Line End Comment
Annotation qualifier "//", you can comment out the whole line or a part of a line. It is generally not used for consecutive lines of comment text, however, it can be used to comment out a number of consecutive lines of code snippets. Here are a few examples of all three styles:


if (Foo > 1) {

Do a double-flip.
...
}
else {
return false; Explain why here.
}

if (Bar > 1) {
//
Do a triple-flip.
// ...
//}
else {
return false;
//}

5.2 Documentation Comments
Note: A sample of the annotation format described here, see "Examples of Java source files"

For more information, see "How to Write Doc Comments for Javadoc", which contains info about documentation comment marks (@return, @param, @see):

Http://java.sun.com/javadoc/writingdoccomments/index.html

For more information about documentation comments and Javadoc, see the home page of Javadoc:

Http://java.sun.com/javadoc/index.html

Document annotations Describe Java classes, interfaces, constructors, methods, and fields (field). Each document comment is placed in the annotation delimiter/**...*/, and one annotation corresponds to a class, interface, or member. The comment should precede the declaration:

/**
* The Example class provides ...
*/
public class Example {...

Note that the top-level (top-level) classes and interfaces are not indented, and their members are indented. The first line of the document annotation that describes the class and interface (/**) does not need to be indented, and subsequent document comments are indented to 1 cells per line (align the asterisk vertically). Members, including constructors, indent the first line of the document annotation by 4, followed by a indentation of 5 cells per line.

If you want to give information about a class, interface, variable, or method that is not suitable for writing in a document, you can use the implementation block annotation (see 5.1.1) or a single-line comment immediately following the declaration (see 5.1.2). For example, details about a class implementation should be placed in the implementation block comment immediately following the class declaration, rather than in the document comment.

Document comments cannot be placed in the definition block of a method or constructor because Java will associate the first declaration that follows a document comment.

6 statement

6.1 The number of declared variables per line

A single statement is recommended because it facilitates the writing of annotations. i.e.

int level; Indentation level
int size; Size of table

To better Than,

int level, size;

Do not put declarations of different types of variables on the same line, for example:

int foo, fooarray[]; wrong!

Note: In the example above, a space is placed between the type and the identifier, and another allowed alternative is the use of tabs:


Intlevel; Indentation level
Intsize Size of table
Objectcurrententry; Currently selected table entry


6.2 Initialization
Try to initialize the local variable while declaring it. The only reason for not doing this is that the initial value of the variable depends on some previously occurring calculation.

6.3 Layout

Declare a variable only at the beginning of the code block. (a block refers to any code that is enclosed in the middle of the braces "{" and "}".) Do not declare the variable when it is first used. This can confuse programmers who are distracted, while interfering with the portability of your code within that 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 for the FOR loop

for (int i = 0; i < maxloops i++) {...}

Avoid declaring a local variable that overrides a variable declared at the previous level. For example, do not declare the same variable name in an internal code block:

int count;
...
MyMethod () {
if (condition) {
int count = 0; avoid!
...
}
...
}


6.4 Declarations of classes and interfaces
When writing classes and interfaces, you should adhere to the following formatting rules:

-Do not have spaces between the opening parenthesis "(") before the method name and its argument list
-The opening brace "{" is at the end of the statement peer
-The right Brace "}" is on a separate line, aligned with the corresponding declaration statement, unless it is an empty statement, "}" should be immediately after "{"

Class Sample extends Object {
int ivar1;
int ivar2;

Sample (int i, int j) {
Ivar1 = i;
Ivar2 = j;
}

int Emptymethod () {}

...
}

-Null line separation between method and method

7 statements

7.1 Simple Statements

Each line contains at most one statement, for example:

argv++; Correct
argc--; Correct
argv++; argc--; avoid!


7.2 Compound Statements
A compound statement is a sequence of statements contained in curly braces, in the form of "{statement}". For example, the following paragraphs.

-The statements that are enclosed should be indented one level more than compound statements
-The opening brace "{" should be at the end of the line at the beginning of the compound statement, and the closing brace "}" should be on a separate line and aligned with the first line of the compound statement.
-curly braces can be used for all statements, including individual statements, as long as they are part of a if-else or for control structure. This makes it easy to add statements without having to worry about introducing bugs by forgetting braces.

7.3 Return statement

A return statement with the returned value does not use parentheses "()" unless they somehow make the return value more visible. For example:

Return

return Mydisk.size ();

return (size size:defaultsize);


7.4 if,if-else,if else-if Else statement
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 enclosed in "{" and "}", avoid the following error-prone formats:

if (condition)//avoid! This omits the braces {}!
Statement


7.5 For statement
A For statement should have the following format:

for (initialization; condition update) {
statements;
}
An empty for statement (all work in initialization, conditional judgment, UPDATE clause completion) should have the following format:

for (initialization; condition; update);
When using commas in initialization or update clauses of a for statement, avoid using more than three variables, resulting in increased complexity. If necessary, separate statements can be used before the for loop (for initialization clauses) or at the end of the For loop (for UPDATE clauses).

7.6 While statement

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

A do-while statement should have the following format:

do {
statements;
while (condition);
7.8 switch statement
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
}

Whenever a case goes down (because there is no break statement), you should usually add a comment at the location of the break statement. The example code above contains comments/* Falls through * *.

7.9 Try-catch Statement

A try-catch statement should have the following format:

try {
statements;
catch (Exceptionclass e) {
statements;
}
A Try-catch statement may also follow a finally statement, which is executed regardless of whether the try code block is executed successfully.

try {
statements;
catch (Exceptionclass e) {
statements;
finally {
statements;
}

8 Blank

8.1 Blank Lines
The empty rows are separated by logically related code segments to improve readability.

You should always use two blank lines in the following situations:

-Between two fragments (section) of a source file
-Between the class declaration and the interface declaration

You should always use a blank line in the following situations:

-Between two methods
-The first statement of a local variable and method within a method
-Block Comment (see "5.1.1") or single-line comment (see "5.1.2")
-Two logical segments within a method to improve readability

8.2 Spaces

Spaces should be used in the following situations:

-a keyword that follows the parentheses should be separated by a space, for example:

while (true) {
...
}

Note: Spaces should not be placed between the method name and its left parenthesis. This will help to differentiate between keywords and method calls.
-whitespace should be in the argument list after the comma
-All two-dollar operators, except ".", should be separated from the operands using a space. There is no space between unary operators and operands, such as: Minus sign ("-"), self-increasing ("+ +"), and self-subtraction ("--"). For example:
A + + C + D;
A = (A + b)/(c * d);

while (d++ = s++) {
n++;
}
PrintSize ("size is" + foo + "\ n");

-the expression in the For statement should be separated by a space, for example:
for (EXPR1; expr2; expr3)

-Forced transformation should be followed by a space, for example:
MyMethod ((Byte) Anum, (Object) x);
MyMethod ((int) (CP + 5), ((int) (i + 3)) + 1);

9 Naming conventions
Naming conventions make programs easier to read and easier to understand. They can also provide some information about the function of identifiers to help understand the code, for example, whether it is a constant, a package, or a class.

Identifier type naming rule example
Package (Packages) The prefix of a unique package name is always all lowercase ascii letters and is a top-level domain, usually com,edu,gov,mil,net,org, or the English two-character code of the identity country specified in the 1981 ISO 3166 standard. Subsequent portions of the package name vary according to the respective internal naming conventions of each organization. This type of naming convention may distinguish a department (department), Project (project), Machine (machine), or registered name (login names) in the form of a specific directory name. Com.sun.eng
Com.apple.quicktime.v2
Edu.cmu.cs.bovik.cheese
Class (Classes) naming rule: A class name is a noun that is mixed in a case-sensitive way, with the first letter of each word capitalized. Try to make your class name concise and descriptive. Use complete words to avoid abbreviations (unless the acronym is more widely used, like url,html) class Raster;
Class Imagesprite;
Interface (interfaces) naming rules: Casing rules are similar to class names interface rasterdelegate;
interface storing;
Method (Methods) method name is a verb, in a case-sensitive way, the first letter in lowercase, followed by the first letter of the word uppercase. Run ();
Runfast ();
Getbackground ();
Variable (Variables) in addition to variable names, all instances, including classes, class constants, are mixed in case, the first letter is lowercase, and then the first letter of the word is capitalized. Variable names should not begin with an underscore or dollar sign, although this is syntactically permissible.
Variable names should be short and descriptive. The choice of variable name should be easy to remember, that is, can point out its use. Try to 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, and they are generally used for integers; c,d,e, which are generally used for character types. char c;
int i;
float Mywidth;
Instance variables (Instance Variables) have similar capitalization rules and variable names, except that an underscore int _employeeid is required before;
String _name;
Customer _customer;
The declarations of constant (Constants) class constants and ANSI constants should all be capitalized and the words should be separated by an underscore. (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 to instance and class variables

If there is not enough reason, do not declare the instance or class variable as public. Typically, an instance variable does not require explicit setting (set) and fetch (gotten), which is usually generated as an edge effect (side effect) of the method invocation.

A proper example of a public instance variable is that the class is only a data structure and has no behavior. That is, if you are using a struct (struct) rather than a class (if the Java support structure), then it is appropriate to declare the instance variables of the class as public.

10.2 Reference class variables and class methods

Avoid using an object to access static variables and methods of a class. Should be replaced with the class name. For example:

Classmethod (); Ok
Aclass.classmethod (); Ok
Anobject.classmethod (); avoid!


10.3 Constants
A numeric constant that is the counter value in the For loop, except for -1,0 and 1, should not be written directly to the code.

10.4 Variable Assignment

Avoid assigning multiple variables to the same value in one statement. It's hard to read. For example:

Foobar.fchar = Barfoo.lchar = ' C '; avoid!

Do not use assignment operators where they are easily confused with the equality relational operator. For example:

if (c + + = d++) {//avoid! (Java disallows)
...
}

should be written


if ((c + + = d++)!= 0) {
...
}

Do not use the inline (embedded) assignment operator to try to increase the efficiency of the runtime, which is the work of the compiler. For example:

D = (A = B + c) + R; avoid!

should be written

A = B + C;
D = A + R;


10.5 Other conventions

10.5.1 parentheses
In general, it is a good way to use parentheses in an expression that contains multiple operators to avoid operator precedence problems. Even though the precedence of an operator may be clear to you, it is not necessarily the case for others. You can't assume that other programmers are as aware of the precedence of operators as you are.

if (A = = b && c = d)//avoid!
if ((a = = b) && (c = d))/right

10.5.2 return value
Try to keep your program structure in line with your purpose. For example:

if (booleanexpression) {
return true;
} else {
return false;
}

The following should be used instead:

return booleanexpression;
Similar to:

if (condition) {
return x;
}
return y;

should be written:

return (condition x:y);



10.5.3 conditional operator "?" The previous expression
If an expression containing a two-dollar operator appears in the ternary operator "? : "The"? " , you should add a pair of parentheses to the expression. For example:

(x >= 0)? x:-X;

10.5.4 Special Notes
Use XXX in a note to identify some of the bogus (work)-capable content. Use Fixme to identify certain false and erroneous content

11 code example

11.1 Java Source Files Example

The following example shows how to reasonably lay out a Java source program that contains a single common class. The layout of the interface is similar. See "Class and interface Declarations" and "text-blocking annotations" for more information.


/*
* @ (#) Blah.java 1.82 99/03/18
*
* Copyright (c) 1994-1999 Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, California, 94303, and U.S.A.
* All rights reserved.
*
* This software is the confidential and proprietary information of Sun
* Microsystems, Inc. ("Confidential Information"). Shall not
* Disclose such confidential information and shall use it
* accordance with the terms of the license agreement your entered into
* with Sun.
*/


Package Java.blah;

Import Java.blah.blahdy.BlahBlah;

/**
* Class description goes here.
*
* @version 1.82 1999
* @author Firstname Lastname
*/
public class Blah extends SomeClass {
/* A class implementation comment can go. */

/** CLASSVAR1 Documentation Comment * *
public static int classVar1;

/**
* CLASSVAR2 documentation comment that happens
* More than one line long
*/
private static Object classVar2;

/** INSTANCEVAR1 Documentation Comment * *
Public Object instanceVar1;

/** INSTANCEVAR2 Documentation Comment * *
protected int instanceVar2;

/** INSTANCEVAR3 Documentation Comment * *
Private object[] INSTANCEVAR3;

/**
* ... constructor blah documentation comment ...
*/
public blah () {
... implementation goes here ...
}

/**
* ... method dosomething documentation Comment ...
*/
public void dosomething () {
... implementation goes here ...
}

/**
* ... method dosomethingelse documentation Comment ...
* @param someparam Description
*/
public void Dosomethingelse (Object someparam) {
... implementation goes here ...
}
}



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.