Java coding specifications (1)

Source: Internet
Author: User
Java coding specification (1)-General Linux technology-Linux programming and kernel information. For details, see the following section. 2. File Names)
This section lists common file names and their suffixes.
2.1 File suffix (File Suffixes)
Java programs use the following file suffixes:
File category file suffix
Java source file. java
Java bytecode file. class
2.2 Common File Names)
Common file names include:
Object Name Purpose
The preferred file name for GNUmakefile makefiles. We use gnumake to create (build) software.
README overview preferred file names for files contained in a specific directory
3. File Organization)
A file consists of paragraphs separated by blank lines and Optional comments that identify each paragraph. Programs with more than 2000 rows are hard to read and should be avoided as much as possible. The "Java source file example" provides a Java program example with a reasonable layout.
3.1 Java Source Files)
Each Java source file contains a single public class or interface. If private classes and interfaces are associated with a public class, you can put them and public classes in the same source file. The public class must be the first class or interface in this file.
Java source files also follow the following rules:
-Start annotation (see "Start annotation ")
-Package and Import Statement (see "package and Import Statement ")
-Class and interface declaration (see "class and interface declaration ")
3.1.1 start with Comments (Beginning Comments)
All source files should start with a C-language annotation, listing the class name, version information, date, and copyright statement:
/*
* Classname
*
* Version information
*
* Date
*
* Copyright notice
*/

3.1.2 Package and Import Statements)
In most Java source files, the first non-Comments line is a package statement. After that, you can introduce the statement. For example:
Package java. awt;

Import java. awt. peer. CanvasPeer;

3.1.3 Class and Interface Declarations)
The following table describes the parts of the class and interface declaration and their order of appearance. For more information, see "Java source file example.
Annotation of each part of the class/interface declaration
Class 1/interface document annotation (/**...... */) The information to be included in the comment. For more information, see "document comment"
Declaration of two types or interfaces
Annotations for Class 3/interface implementation (/*...... */) If necessary, the comment should contain any information about the entire class or interface, which is not suitable for commenting on the class/interface document.
Class 4 (static) variables are first the public variables of the class, followed by the protection variables, then the variable at the package level (no access modifier, access modifier), and finally the private variables.
5. The instance variables are at the public level first, followed by the protection level, followed by the package level (no access modifier), and finally the private level.
6 Constructor
7. These methods should be grouped by functions, rather than scope or access permissions. For example, a private class method can be placed between two public instance methods. The purpose is to facilitate reading and understanding the code.
4. Indentation)
Four spaces are often used as a unit of indentation. The exact description of indentation is not specified in detail (space vs. Tab ). A tab is equal to eight spaces (not four ).
Line Length)
Avoid a line with more than 80 characters, because many terminals and tools cannot handle it well.
Note: The example used in the document should use a shorter length, which generally cannot exceed 70 characters.
4.2 wrap (Wrapping Lines)
When an expression cannot be contained in a row, it can be disconnected according to the following general rules:
-Disconnected after a comma
-Disconnected before an operator
-Select a higher-level disconnection, rather than a lower-level disconnection.
-The new row should be aligned with the beginning of the expression of the previous row at the same level.
-If the above rules cause your code to be chaotic or make your code pile up on the right side, place them with eight spaces.
The following are examples of method call disconnection:
SomeMethod (longExpression1, longExpression2, longExpression3,
LongExpression4, longExpression5 );

Var = someMethod1 (longExpression1,
SomeMethod2 (longExpression2,
LongExpression3 ));

The following is an example of two disconnected arithmetic expressions. The former is better, because the disconnection 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

The following is an example of two indent method declarations. The former is a general situation. If the latter uses the regular indent method, it will move the second and third rows to the right, so it will be indented with 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 line feed of if Statements usually uses eight spaces, because regular indentation (4 spaces) makes the statement body look hard. For example:
// DON't USE THIS INDENTATION
If (condition1 & condition2)
| (Condition3 & condition4)
|! (Condition5 & condition6) {// BAD WRAPS
DoSomethingAboutIt (); // MAKE THIS LINE 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 ();
}

There are three feasible methods for processing the ternary expression:
Alpha = (aLongBooleanExpression )? Beta: gamma;

Alpha = (aLongBooleanExpression )? Beta
: Gamma;

Alpha = (aLongBooleanExpression)
? Beta
: Gamma;
5 Comments)

Java programs have two types of Annotations: implementation comments and document comments ). Implementation annotations are those that have been seen in C ++ and are defined using/*... */and. Document comments (known as "doc comments") are unique to Java and are defined. You can use javadoc to convert document comments into HTML files.

Implementation annotations are used to annotate code or implementation details. Document comments describe code specifications from the perspective of implementation-free. It can be understood by developers who have no source code at hand.

Annotations should be used to give a summary of the Code and provide additional information that the Code itself does not provide. Annotations should only contain information related to reading and understanding programs. For example, information such as how the corresponding package is created or in which directory should not be included in the comment.

In comments, it is okay to describe the important or not obvious aspects of design decisions, but avoid providing repeated information clearly expressed in the code. Additional comments are easily outdated. Generally, comments that may be out of date due to code updates should be avoided.

Note: frequent comments sometimes reflect the low quality of the Code. When you feel forced to add comments, consider rewriting the Code to make it clearer.

Comments should not be written in a large box drawn with asterisks or other characters. Comments should not contain special characters such as tabs and rollbacks.

5.1 implement the annotation format (Implementation Comment Formats)

The program can have four annotation styles: block, single-line, trailing, and end-of-line ).

5.1.1 Block Comments)

Block annotations are usually 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 in other places, such as internal methods. Block comments inside functions and methods should have the same indent format as the code they describe.

There should be a blank line at the beginning of the block comment to separate the block comment from the code, for example:


/*
* Here is a block comment.
*/


The block annotation can start with/*-, so that indent (1) can recognize it as the beginning of a code block without shuffling it.


/*-
* Here is a block comment with some very special
* Formatting that I want indent (1) to ignore.
*
* One
* Two
* Three
*/


Note: if you do not use indent (1), you do not need to use/*-in the Code, or make concessions for others to run indent (1) on your code.

See "document notes"

5.1.2 Single-Line Comments)

A short comment can be displayed in a row and has the same indentation level as the subsequent code. If a comment cannot be written in one line, block comment should be used (see "Block comment "). There should be a blank line before a single line comment. The following is an example of a single line comment in Java code:


If (condition ){

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

5.1.3 end Comments (Trailing Comments)

Very short comments can be in the same line as the code they want to describe, but there should be enough white space to separate the code and comments. If multiple short comments appear in a large code segment, they should have the same indentation.

The following is an example of an end-to-end comment in Java code:

If (a = 2 ){
Return TRUE;/* special case */
} Else {
Return isPrime (a);/* works only for odd */
}


5.1.4 End-Of-Line Comments)

The annotator "//". You can comment out a part of the entire line or a row. It is generally not used for comments of multiple consecutive rows; however, it can be used to comment out code segments of multiple consecutive rows. The following are 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: For an example of the annotation format described here, see "Java source file example"

For more information, see "How to Write Doc Comments for Javadoc", which contains information about the document annotation mark (@ return, @ param, @ see ):

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

For more information about document comments and javadoc, see the javadoc homepage:

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

This document describes Java classes, interfaces, constructors, methods, and fields ). Each document comment is placed in the comment ing/**... */. A comment corresponds to a class, interface, or member. The comment should be prior to the Declaration:


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


Note that top-level classes and interfaces are not indented, and their members are indented. The first line (/**) of the document comment for the description class and interface does not need to be indented; each line of the subsequent document comment is Indented by 1 (vertical alignment of the asterisk ). Member, including the constructor, the first line of the comments in the document is Indented by 4 cells, and then each line is Indented by 5 cells.

If you want to provide information about classes, interfaces, variables, or methods that are not suitable for writing in the document, you can use implementation block annotations (see 5.1.1) or a single line comment that follows the declaration (see 5.1.2 ). For example, the implementation details of a class should be placed in the implementation block comment followed by 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 associates the first declaration after the document comments with it.

6 Statement (Declarations)

6.1 Number of variables declared Per Line)

A declaration is recommended for one row, as this facilitates writing comments. That is,


Int level; // indentation level
Int size; // size of table


Better,

Int level, size;

Do not place declarations of different types of variables in the same row. For example:


Int foo, fooarray []; // WRONG!


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


Int level; // indentation level
Int size; // size of table
Object currentEntry; // currently selected table entry


6.2 Initialization)

Try to initialize the local variable while declaring it. The only reason for not doing so is that the initial value of the variable depends on some previous calculations.
Related Article

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.