Java coding specifications (reprint)

 Coding Standards

1 Introduction
To ensure the readability of the source system to enhance maintainability, java programmers should have substantially similar programming style, hereby formulate the following Java programming specification to standardize the system Java Programming. Other resources in the source system inherited Click specifications should be amended accordingly.

2 Scope
This document will regulate as a java programmer software development programming format. In the coding, testing and maintenance projects in the Java part, it requires strict adherence.

3 naming conventions
define the purpose of this specification is to allow all project documents are written to look like a man, to increase readability and reduce losses in the team because of substitutions brought.

3.1 Package named the
Package names should be lowercase words are from a composition. Example: unipost.trans

Named 3.2 Class of
Class names must begin each word in capital letters and the other letters are lowercase-word. Example: FileMng

3.3 Class members named
variables, methods, properties: the case of shuffling-word, the first letter lowercase

Example: functionName, countNum, size

3.4 Static Final naming variables
Static Final constants: the composition of capitalized words, between the use of the word "_" connection

Example: MAX_INDEX

3.5 Taiwan before and after the variable name
foreground variable fg_ variable name

Background variables bg_ variable name

3.6 named parameter
name parameter must match the naming conventions of variables.

3.7 Naming an array of
arrays should always be named in the following way:

 

 

3.8 parameter method of
use meaningful parameter name, if possible, and use the properties to be assigned the same name:

 

 

3.9 Abbreviations
some common abbreviations may be used, such as:

temp may be abbreviated as tmp;

message may be abbreviated MSG;

3.10 identifier should be noted that nomenclature issues
3.10.1 addition to local loop variable fetch prohibited single character variable name
for the variable name, a single fetch prohibited character (e.g., i, j, k ...), suggests that in addition to have the specific meanings outer , which also indicates that the variable type, data type, etc., but i, j, k for the local loop variables are permissible.

Description: Variable, in particular, is a local variable, if represented by a single character, it is easy to mistype (written as i j), and compile time and check it out, it is possible for this small mistake and spend a lot of time troubleshooting.

3.10.2 numbers do not define names
unless absolutely necessary, do not use numbers or identifiers to define the more strange characters.

Example: The following names, gives rise to doubt.

void set_sls00( BYTE sls );

It should be replaced by meaningful words naming

void setUdtMsgSls( BYTE sls );

3.10.3 named with the correct antonym group
function named variables have mutually exclusive meaning with the correct antonym or opposite set of actions and so on.

Description: Here are some commonly used in software antonyms group.

 

 

3.10.4 avoid the use
should be avoided _EXAMPLE_TEST_ like to underscore the start and end of the definition.

4 style
4.1 Java style file
all of the Java (*. Java) files must comply with the following style rules

4.1.1 Copyright information
Copyright information must be at the beginning of java files, example:

 

 

The Package 4.1.2 / Imports
Package row to row before import, import standard package before the local name to the package name, and in alphabetical order. If the import line contains a different subdirectory of the same package, it is recommended to deal with *.

 

 

4.2 Class of style
definitions 4.2.1 Class of
containing extends and implements different rows in

 

 

4.2.2 Class Fields
class member variables:

 

 

public member variables must be annotated and must generate documentation (JavaDoc).

proceted, private and package variables if the names of members of defined meaning clear, you can not comment.

4.2.3 Constructor
constructor, it should be written in an incremental manner (for example: parameters and more written on the back).

 

Method 4.2.4 Cloning
If the class can be cloned:

 

 

Written order of member variables and methods of class 4.2.5
recommendations written order:

public  protected  private

final    static     transient

4.2.6 main method
if the main (String []) method has been defined, it should be written at the bottom of the class.

4.3 Code Style
Code unix format should be used instead of the windows (for example: Enter into carriage return + line)

Note 5
5.1 general
source Note effective amount must be at least 20%.

Description: Comment principle is to contribute to the understanding of reading programs, the increase in places that are added, the comment should not be too much nor too little, annotation language must be accurate, easy to understand, simple.

5.2 General Comment SIGNS
Comment Starts with "/ * ... * /", the first for the concluding statement of the annotated document, you can use HTML tags in the comment statements in the document, but to eliminate the use of "HL" "HR" label. Notes used in all Chinese, and to write specifications in accordance with the following tags.

@Since 5.2.1
@Since text: You can generate a "since" entry by one of the "text", a feature that can be explained "since" Which version introduced in the beginning.

@Deprecated 5.2.2
@deprecated Text: increase a comment, specify a particular class, method or variable should not be used here, deprecated is "not in favor" and "not recommended" means. Use one of the "text", another method may be recommended to the user to achieve the same purpose. Such as:

1
2
3
4
/**
    ...
    @deprecated 使用setVisible
*/

@See 5.2.3
@see link: Add a hyperlink.

5.2.3.1 If the point class, method or variable name
may be written directly after the @see class, method or variable names may be omitted packet writing method, class name, default properties for the current class or package. Note: classes, methods, among variable names using the "#" to separate.

 

5.2.3.2 If the point to a specific URL, directly writing HTML anchor tag.

 

5.2.3.3 If a pointer points to the "seeAlso (Reference)" section is displayed, using the "" "" (double quote).

 

@Link 5.2.4
@link: can establish special hyperlinks in comments, so that it points to other classes or methods, labeling rules with @see.

5.3 classes and interfaces of notes
based annotation must be placed after any import statement, while in front of the class definition.

@author name: the establishment of a "author" entry.

@version text: create a "version" entry.

5.4 Method of notes
immediately before each method must have the signature of a method that it describes.

@param variable description: "parameters" (parameters) section to add an entry.
@return description: Add a "returns" (return value) section.
@throws class description: as "throws" method (generating violation) add an entry section.

 

6 Writing format specification
6.1 coding specification
6.1.1 indentation
indentation should be four spaces in each row, when a different source code management tool Tab characters will be set by the user because of the different expansion of different widths.

If you use UltrEdit as your Java source code editor, you can disable save Tab character by operations, methods by UltrEdit the first set length of Room 4 spaces Tab use, and then use Format | Tabs to Spaces menu convert Tab to spaces.

Under the deal with the case statement case statement should also comply with the requirements indented statement.

6.1.2 The page width
page width should be set to 80 characters. Source code normally does not exceed the width, and can not lead to a full display, but this setting can be flexibly adjusted. In any case, long sentences should be a comma or one operator off-line post. the latter statement is wrapped, four characters should be indented than the original statement.

Example:

permCountMsg.Head.Len  =  NO7_TO_STAT_PERM_COUNT_LEN

+  STAT_SIZE_PER_FRAM * sizeof( _UL );

actTaskTable[FrameID * STAT_TASK_CHECK_NUMBER + index].Occupied

= statPole[index].occupied;

6.1.3 blank lines
between the independent blocks, after the blank lines must be added to variable declaration.

 

 

6.1.4 space used 
when more than two key variables, constants and the like of the operation, the operator between them before, after, or around a space to increase; when the non-peer to peer operations, if it is close Now operator (e.g., ->), should the spaces.

Description: The purpose of this code is written in a loose way is to make more clear the code.

It should not appear between the left parenthesis after a character space and, equally, should not be any space between the right parenthesis and the previous character following examples illustrate brackets and spaces mistakes and correct use:

CallProc (AParameter); // error

CallProc (AParameter); // correct

{6.1.5} usage
block delimiters (e.g., braces '{' and '}') each on its own line and should be in the same column, while statements that reference them with left-justified. In the beginning of the function of the definition of class definition of the structure, and the definition of the enumeration if, for, do, while, switch, case statement must procedure as above using indentation.

 

 

 

 

6.1.6 if other statements written
if, for, do, while, case, switch, default, try, catch and other statements line by itself, "{" must be written back to the line, and the execution if, for, do, while other statements of statement section must be enclosed in {} return prepared, if only one statement execution, {} may be the default.

Example: The following example does not meet specifications.

if (pUserCR == NULL) return;

It should be written as follows:

if (pUserCR == NULL)

{

    return;

}

6.1.7 cycle and judgment statement
cycle and judgment statement if the statement or expression longer, will have to be appropriately divided, dividing the new long expression to the low priority line operator, the operator on the the first of the new line.

 

 

6.1.8 division parameter
when the method arguments are longer will have to be appropriately divided.

 

 

6.1.9 line write only one statement
is not allowed to write more short statements on one line, that line of writing only one statement.

Example: The following example does not meet specifications.

rect.length = 0;  rect.width = 0;

It should be written as follows

rect.length = 0;

rect.width  = 0;

6.2 Variable preparation of specifications
6.2.1 Public variables
6.2.1.1 remove unnecessary public variables.
Description: common variable is one of the reasons of increasing the coupling between modules, it should reduce unnecessary common variable to reduce the coupling between modules.

6.2.1.2 carefully define and clarify the relationship between the meaning of public variables, functions, ranges and public variables.
Description: While on variable declarations, to deal with its meaning, function and value range of notes, and if necessary also the relationship with other variables.

6.2.1.3 When variables to pass data to the public, be very careful to prevent unreasonable and so endowed with value or cross-border phenomenon.
Description: When a public variable assignment, if necessary, should be carried out to check the legitimacy, in order to improve code reliability and stability.

6.2.2 Local variables
6.2.2.1 prevent local variables and common variables of the same name.
Note: If you use a good naming convention, so this problem can be automatically eliminated.

6.3 programming specification
6.3.1 Exit ()
Exit can be invoked in addition to the main, other places should not be called. Because it does not give any chance to intercept the code to exit. A similar background service program should not be a library module because of a decision to withdraw from the exit.

6.3.2 abnormal
declared a RuntimeException or error should throw an exception derived. Affirming errors mainly refers precondition violation, case processing flow violations. The branch suggestions of using return values.

The module configuration exception recommended, by way of gradual process, and printing (or logged). The same module-level exception, according to the functions of a module can be centralized treatment.

6.3.3 garbage collection
JAVA garbage collection using a sophisticated back-end technology to replace the reference count. But this will cause a problem: you have to clearance work done at a later instance object (an object is placed after the NULL, automatic reference counting -1).

6.3.4 final class
is definitely not because of performance reasons, the class is defined as final (unless required framework program)

If a class is not ready to be inherited, best noted in the comments, but not want to define it as final. This is because no one can guarantee that will not need to inherit any reason.

6.3.5 access the class member variables
most of the class should be defined as private member variables of the derived class to prevent the use of them.

7 Programming Skills
7.1 General principles
7.1.1 check the validity of all input parameters.
7.1.2 Check the input parameters
to check the validity of all non-input parameters, such as data files, such as public variables.

Description: There are two main inputs: one is an input parameter; the other is a global variable, input data file, i.e., non-parametric input. Before using the input, should carry out the necessary checks.

7.1.3 The class name should accurately describe the function of the class.
7.1.4 avoid forced return type
unless absolutely necessary, and it is best not to return a different value type variable to compile the system default or mandatory conversion mode conversion method as a return value to return.

7.1.5 allows call sites seem to understand, easy to understand.
7.1.6 reduce data type conversion
when filling out the parameters, should minimize unnecessary default data type conversion or mandatory data type conversion.

Description: Because the data type conversion danger or less.

7.1.7 prevent spam code for the program.
Description: Garbage code in a program not only take up extra space, but also often affect the function and performance of the program, is likely to test procedures, maintenance cause unnecessary trouble.

7.1.8 reduce recursive call.
Description: recursive call intelligibility impact of the program; recursive call generally take up more system resources (such as stack space); recursive calls have some influence on the test program. Unless it easy to achieve certain algorithm or function, should reduce unnecessary recursive calls.

7.1.9 Use data flow diagrams
careful analysis of functional and performance requirements of the module, and further broken down, and if necessary to draw the relevant data flow diagram.

Description: Mapping the structure of one of the common method is a functional diagram of the module or / and the data flow graph.

7.1.10 Avoid using BOOL parameters.
Description: There are two reasons, one is BOOL parameter value is meaningless, meaning TURE / FALSE is very vague, it is difficult to know when to call in the end to convey the parameters of what is meant; the other is BOOL parameter value is not conducive to expansion. There NULL is a meaningless word.

7.2 development process skills
7.2.1 byte array is converted to characters
in order to convert the byte array to characters, you can do this:

"Hello world!".getBytes();

7.2.2 Utility class
Utility class (only to provide a method of class) should be declared as abstract to prevent inheritance or initialized.

7.2.3 array initialization
following code is a good way to initialize the array:

objectArguments = new Object[] { arguments };

7.2.4 enumerated type
JAVA bad for the enumeration of support.

 

This technology enables constant may like other languages as enumerated type used RED, GREEN, BLUE and so on. They can be compared with == operator. 
But such use has a flaw: If a user in such a way to create a color BLACK

new Colour (0,0,0), then this is another subject. == operator error occurs. Her equal () method is still valid. For this reason, this technique is best noted defects, or only in their own bag in the document.

7.2.5 Swing
avoid using AWT components 
mix AWT and Swing components 
if you want to AWT components and Swing components mixed use, please use caution. In fact, try not to mix them up and use.

Rolling AWT components 
AWT components Never be achieved by rolling JscrollPane class. When rolling AWT components must use AWT ScrollPane component to achieve.

Avoid using AWT components in the assembly InternalFrame 
try not to do it, or else there will be unpredictable consequences.

7.2.6 Z-Order problem
AWT components are always displayed on top of Swing components. When using the POP-UP menu contains AWT components to be careful, try not to use this.

7.2.7 unnecessary objects constructed 
not to construct and release objects in a loop

7.2.8 synchronized keyword
avoid too much use of synchronized keyword

Avoid unnecessary use of keyword synchronized, should no longer use it when necessary, this is a good way to avoid a deadlock.

Borland Jbulider do not like the synchronized keyword, if you set a breakpoint in the scope of these keywords, then breakpoints when debugging you will find that will bounce around, so you know what to do. Unless it is necessary, try not to use.

7.3 Efficiency Program
7.3.1 attention to the efficiency of the code
should always pay attention to the efficiency of the code programmed.

Description: code efficiency divided into global efficiency, local efficiency, time efficiency and space efficiency. The overall efficiency of the system is standing on the efficiency of the overall system perspective; stand on local efficiency is a function of angle, or efficiency of the module; time efficiency is the length of time required for program processing the input task; space efficiency program memory space is required, such as machine code space, the size of the data space, the stack space size.

7.3.2 code efficiency
in accuracy, stability, and readability provided to ensure testability system, code efficiency.

Description: You can not blindly pursue code efficiency, and correctness of the software, stability, readability and testability impact.

7.3.3 Local efficiency should serve as a global efficiency of
local efficiencies should serve as a global efficiency, can not but affect the overall efficiency because improve local efficiency.

7.3.4 vivo circulating minimize workload.
Description: The body of the loop should carefully consider whether the statement can be placed outside the loop, the loop body minimal effort, thereby enhancing the efficiency of the program period.

 

 

7.3.5 careful analysis of algorithms, and optimized.
7.3.6 improved input mode
scrutinize the analysis system and process input modules (e.g., transaction, message, etc.) manner and make improvements.

7.3.7 calls are not frequent improve the efficiency of the code to be careful
not to spend too much time calling desperately to improve the efficiency of the code is not very frequent.

Description: The code optimization can improve efficiency, but if ill-considered likely to cause serious consequences.

7.3.8 improve space efficiency
in the premise of ensuring the quality of the program, the code amount by compressing, removing unnecessary code, and reduce unnecessary local and global variables, to enhance the space efficiency.

Description: This way to improve the space efficiency can play a role, but often can not solve the fundamental problem.

7.3.9 cycle position
in the multi-cycle, should be the busiest in the innermost loop.

Description: reduce the number of CPU cycles cut layer.

 

 

 

 

7.3.10 minimize circulating levels of nesting.
7.3.11 avoid circular body with decision statement
to avoid circular body with decision statement, a loop statement should be placed in the code block is determined statements.

Description: The purpose is to reduce the number of determinations. Determining whether statements in the loop body can be moved vitro cycle, the program depending on the particular case, in general, independent of the loop variable is determined in vitro loop statement can be moved, and not be relevant.

 

 

7.3.12 Do not blindly pursue compact code.
Description: Because the code does not represent a compact and efficient machine code

8 performance
at the time of writing the code, performance issues should be considered from start to finish. This is not to say that the time should be wasted on optimizing the code, but we should remind ourselves time to pay attention to the efficiency of the code. For example: If you do not have time to implement an efficient algorithm, then we should be recorded in the document, in order to realize her again in the future when empty.

Not all people agree that at the time of writing the code should optimize the performance of this view, they think performance optimization issues should be considered again at a later stage of the project, that is, the outline of the program has been achieved in the future.

8.1 Portability
To ensure portability system, you need to pay attention to the following points:

8.1.1 Wrap
if desired wrap, try to use instead of using println "\ n" in the string.

You do not like:

System.out.print("Hello,world!\n");

To do so:

System.out.println("Hello,world!");

Or you configured with a newline character string, such as at least:

String newline = System.getProperty("line.separator");

System.out.print ("Hello world" + newline);

PrintStream 8.1.2
PrintStream has been deprecated (deprecated) used, with PrintWrite instead.

8.2 Testability
8.2.1 Commissioning
in the same item or product groups to a uniform set of commissioning switch and corresponding to a printing method and system integration test FBI prepared, and have a detailed description.

Description: This rule is for a team or group of products.

8.2.2 Commissioning information format string
in the same project or product groups, for measurement printed information string format to have a unified form. At least where the bursts have a module name (or the name of the source file).

Description: Commissioning unified information format facilitates integration testing.

8.2.3 Note that in the programming unit tests
simultaneously programmed to select the appropriate test point unit test, the test code and carefully configured, test, and gives instructions explicitly noted. As a test code section should submodule (module) to facilitate installation and removal of the test code in the module (through the host switch).

Description: testing and preparation for the unit.

8.2.4 Test Preparation
Before the integrated test / system the FBI, to construct a good test environment, test items and test cases, and carefully analyze and optimize test cases to improve test efficiency.

Description: Good test case should simulate as a boundary value of the program encountered a variety of complex environments and some extreme cases and so on.

8.2.5 Test methods
to set and cancel the test means in the software system, it can not affect the functions implemented in software.

Description: namely software testing software code and turn off the test code should be consistent with the functional behavior.

8.2.6 Commissioning switch
with commissioning software switch to switch the DEBUG version and the official version, but do not exist at the same time the official version and the version of DEBUG different source files, in order to reduce the difficulty of maintenance.

8.2.7 debugging and testing
before writing the code, should be pre-designed program debugging and testing methods and means and a good design and a variety of switches corresponding commissioning test code, such as print function or the like.

Description: debugging and testing program is a very important phase of the software life cycle, how to conduct a more comprehensive software, test high rate of errors in the software and find out as much as possible has become a very critical issue. So before you write the source code, in addition to a set of fairly complete test plan, we must also design a series of code testing tools for unit testing, integration testing and system FBI ease.

8.2.8 Commissioning switch level and type of
commissioning switch should be divided into different levels and types.

Description: Sets the commissioning and classification switch should consider the following aspects: Commissioning system for a module or portions of code; Commissioning or a functional module for the system; for some other purposes, such as performance, capacity, etc. test. Doing so facilitates commissioning software functions, the module unit and facilitate testing, the FBI and other systems.

8.2.9 prevention program written in the wrong
write error prevention program, and then after processing error available assert declare an error.

Example: If the module receives a message on the communication link, the legitimacy of the message is checked to respond, if the predetermined protocol type is not the message communication, error processing should be carried out

QA 9
9.1 assurance code quality priority principle
(1) the accuracy, refer to programs to implement the functions of the design requirements.
(2) stability, security, the program refers to stable, reliable and safe.
(3) testability, to refer to programs having good testability.
(4) specification / readability, referring to the program coding style, naming rules for compliance.
(5) the overall efficiency refers to the overall efficiency of the software system.
(6) local efficiency refers to the efficiency of itself a module / sub-modules / functions.
(7) Personal expression / personal convenience, refers to personal programming habits.

9.2 Open the file you want to close
the program in the application file handle (used to open files), before the procedure / function exits to be closed.

9.3 consistency check
system operation at the beginning, to be loaded into the data system consistency check.

Note: Use inconsistent data, the system is easy to enter and chaos agnostic.

9.4 switch statement must have a default branch.
9.5 Other quality problems
when using the software development kit or controls provided by third parties, we should note the following:

(1) fully understand the application interface, note the use of the environment and use.

(2) can not be over-confident of its accuracy.

(3) Unless necessary, do not use unfamiliar third-party toolkits and control.

Note: Use Toolkit and controls, can accelerate the speed of application development, saving time, but it must have a more full understanding before use, while third-party toolkits and controls may also be a problem.

Resource files (multi-language version support), if the resource is language-sensitive, should make the resource and the source code files from

10 code editing, compiling, reviewing
10.1 unified compiler environment
in the software product (the project team), we should compile a unified environment, the same JDK version

10.2 commuting and review the code
to check the code through the code review and commuting mode.

(1) mainly for the code programming style commuting procedures such as comments, and other naming and error-prone programming content inspection, by developers or developer their intersecting manner.

(2) code review mainly for functions and procedures of the program to achieve stability, security, reliability, inspection and assessment, through self-examination, cross-audited or designated department checks and other ways.

10.3 QA checks the code
before the test unit test products, QA deal with code checks and review.

10.4 software system directory
rational design of software system directory, easy to developers.

Description: convenient, reasonable software system directory, can improve efficiency. Principle is to facilitate the relevant directory structure of the source program storage, query, compile, link, etc., while the directory should also have a working directory ---- all compilers, links, etc. should be done in this directory, directory tool - - the relevant file editor, file search and other tools can be stored in this directory.

Reprinted address: https: //www.cnblogs.com/ftl1012/p/javaCode.html 1

Guess you like

Origin www.cnblogs.com/zzmds/p/12536408.html