Java Programming specification

Source: Internet
Author: User
Tags log log uppercase letter

I. Preparation of the backgroundThis document is written in a simple way, with most of the content listed in terms or in tabular form, without excessive supplemental instructions, and Code format specifications that follow Eclipse's default coding requirements.
Two. Scope of applicationBackground Developer
General ProvisionsGeneral principles of norm setting? Simple and easy to execute
naming the general principles1. The meaning of the name to be clear, so as to see the name of righteousness, such as: User,role, Usermanager
2. Try to use English name as the variable name, if you want to use Chinese, please write the remarks.
For example: var Hbtype = null;//HB is the acronym for Chinese "Currency".
3. Use mixed-case naming to improve the readability of the name
Correct: Usermanager
Error: Usermanager
4. Use as few abbreviations as possible, but be cautious if you must use them.
You should keep a list of standard abbreviations and be consistent when you use them. For example, to abbreviate the word "number", use the format num, and use only this form. Note: To maintain a list of abbreviated vocabularies.
5. All file names start with uppercase letters, mixed in case, such as userlist.jsp
6. All directory names start with lowercase letters, mixed in case, such as Usertype
7. Variable names cannot begin with an underscore, such as "_account", "_username" is not allowed because a variable beginning with an underscore may be occupied by the Owk platform as a reserved word.
8. Avoid using names that are similar or only differ in case
For example, you should not use variable names PersistentObject and Persistentobjects, as well as Ansqldatabase and ansqldatabase.


Code Annotation Principles1. Comments should be simple and clear, avoid the use of decorative content, that is, do not use a comment statement like ad banners.
2. The purpose of the code comment is to make the code easier to understand for developers who are involved in programming and for other successors.
3. Write the comment first, then write the code.
The best way to write code comments is to write the comments before you write the code. This allows you to think about the function and operation of the code before you write the code. And this ensures that annotations are not omitted. (This works very well if the logic of the program is slightly more complex.)
4. Note that the information should include not only the function of the code, but also the reason.
For example, the code in example 1 below shows that an order with an amount above $1,000 (including $1,000) can give a 5% discount. Why did you do it? Is there a business law that stipulates that large orders can be discounted? Is this a special time limit for large orders, or is it always the case? Did the original program designer just do it because he was generous? Unless they are commented out somewhere (or in the source code itself, or in an external document), you can't know that.
if (grandtotal >= 1000.00)
{
GrandTotal = GrandTotal * 0.95;
}
Three standard contentnamingPackagePackage Structure Definition =${Package unit}[.${Package Unit}]*

Description

1: A package is made up of one or more construction units, with a dot "." between each construction unit. Separated

2: A package unit consists of one or more words
3: The package unit should be a noun
? The package structure of the business system is com.cmb.zct.${Business system name}.${module name}
? The package name is all lowercase, such as: Com.cmb.zct.tx.OA.common is not allowed. But there are cases where uppercase letters are allowed, that is, when a package unit is made up of multiple words. such as: Com.cmb.zct.tx.oa.userType.
class? Use full English descriptors, capitalize the first letter of all words, and mix the uppercase and lowercase words.
? The class name is a noun or noun phrase. as Logmanager
? The tool class ends with Util. such as Fileutil,strutil
? The exception class ends with exception. such as Rootdirnotexistsexception
? Abstract class name begins with abstract abstractgenerator
? The factory class ends with factory, such as Connfactory

? Interface class name, mixed case:

Method? The name of the member function should be in the full English descriptor, mixed in case: capitalize the first letter of all intermediate words. The first word of a member function name often takes a verb with a strong action color. First word lowercase. such as: GetUserInfo, removeequipment
parameter Variables Start with lowercase p
Such as
public void SendMessage (String pMessage) {
...............
}
Note: The JavaBean parameter variable does not take p.
constant NameUse a complete English capital word to connect the word to the word with an underscore.
Max_value,default_start_date
Directory nameThe same package name, beginning with a lowercase letter, and if more than one word is formed, the 2nd Word starts with an uppercase letter. such as user, usertype directory
file nameNaming rules for homogeneous names, beginning with uppercase letters, mixed in case. such as: equipmentlist.jsp
Module-related file naming constraints, in order to facilitate the description, ${model_name} represents the name of the actual module, the names of the files must meet the table format requirements.
file Format examples
Business Component Interface I${model_name}facade.java Iuserfacade.java
Service Component Interface I${model_name}service.java Iuserservice.java
Business component Implementation Class ${model_name}facadeimpl.java Userfacadeimpl.java
Service component Implementation Class ${model_name}serviceimpl.java Iuserserviceimpl.java
Test class ${model_name}servicetest.java Userservicetest.java




Moduleconfiguration file Spring profile ${model_name}.spring.xml User.spring.xml
Sqlmap Configuration ${model_name}.sqlmap.xml User.sqlmap.xml
Seed Files ${model_name}service.seed.xml UserService.seed.xml



Java source file structure

/*
*copyright (c) 2007-2008
*/

Package com.owk.sgtz.util;

Import java.io.Serializable;
Import java.util.List;

/**
*
* @author HO074337
*
*/
public class Test extends Object implements serializable{

/* Variable Comment */
public static final int pkg_header_max_len = 20;
/* */
protected static int i = 0;
int j = 0;
private int k;



/**
* Method Comments
* @param i
*/
Public Test (int i) {

}

/***
* Method Comments
*
*/
public void Printinfo () {

}

}

Description
? The first line is copyright information
? Empty line, define package name
? An empty line that declares the class to import
? An empty line, writing a comment for the class
? Next to each other, define the class
? Empty row, defining variables
? Empty row, defining constructors
? Empty line, defining method


Notesconcept

Java programs have two types of annotations:

Implementation Notes (Implementation comments) and document comments (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. This specification only constrains document annotations, and program comments are self-explanatory by developers, but should follow code-commenting principles

comments for Class/**
*
* @author HO074337
* @version 1.0
* Date Created: 20071010
*
* Function Description:
* The functional description of the class, explaining the main functions of this class
*
* Known Issues:
* If a class has any outstanding problems, it should be explained, so that other developers understand the shortcomings/difficulties of this class.
* In addition, you should also indicate why the problem is not resolved
*
* Maintenance History:
* Lists the date, the author of the class, and the revision summary. The purpose of this is to enable maintenance programmers to understand the past of a
* The changes made by the class, who made the changes
such as
* Huangyh 20071010
* Added the Getuserbyid (String) method, which can be used to obtain the user object
*
* Zhangw 20071008
* Set Private Method Removeuser () to public because the XX module needs to be used.
*
*/

Variable Comment/**
* Maximum length of the communication header
*/
public static final int pkg_header_max_len = 20;
Note: All public, protected, or default variables must be in the document comment notation, as these annotation information needs to be
Export to a document.
Private variable, can be single-line comment, multiline comment, or document comment, do not limit


The variable description describes the purpose of the variable. If it is an enumerated variable, note the range of valid values.

Method Comment/**
* Function Description:
* Method provides what functionality.
*
* Known Issues:
* If there are some problems with the implementation of the method, it needs to be described here so that the subsequent maintenance personnel
* Solve the problem or avoid it.
*
* Use Example:
* Simple Function Call example
*
* @param PMSG Parameter Name parameter description
* @return Return value description
* @exception Exception description
*/


Task CalloutUse Todo in comments to identify some of the things that are not implemented (bogus) but can work (works). Use Fixme to identify certain false and erroneous content.
such as:/**
* todo:xxx validity test.
*/
/**
* Fixme: This code has a serious performance problem, the system must be repaired before the official release
*/
These information can be seen in the Tasks view of Eclipse

Abnormal
1. All business anomalies (no accounts, incorrect passwords, etc.) must be directly or indirectly from Com.cmb.zct.common.exception. Businessexception derivation
2. All system exceptions (primary key conflicts, SQL statements themselves syntax errors) must be derived directly or indirectly from Com.cmb.zct.common.exception.SysException

Log 1. Don't use SYSTEM.OUT.PRINTLN/SYSTEM.ERR.PRINTLN output debugging information
2. Unified use of common log output logs
3. Definition of Log objects

Private final Log log = Logfactory.getlog (Basejdbcdao.class);
Or
Private final static log log = Logfactory.getlog (Basejdbcdao.class);


Encoding MethodSo where coding is involved, all unified use UTF-8 encoding
Programming conventions
1. The class member variable is not set to public unless it is a static final constant
2. The class name is used to access the static method instead of the object. such as: Stringutil.trim
3. Set the constructor of the tool class to private, avoiding the client-side construct object to invoke the tool method
4. Numeric constants that are used as counter values in a for loop, except for -1,0 and 1, should not be written directly to the code. Constant variables should be defined first
5. In general, it is a good practice to use parentheses in expressions that contain multiple operators to avoid operator precedence. Even though the precedence of an operator might be clear to you, it may not be the case for others. You can't assume that other programmers are as aware of the precedence of operators as you do.
if (A = = b && c = = d)//avoid!
if ((a = = b) && (c = = d))//Right
6. For a method that returns LIST/SET/MAP, returns an empty list/set/map instead of NULL when a record does not exist in the collection. There are 3 corresponding empty objects in the Java.util.Collections class Empty_list, Empty_set and Empty_map
7. The key value of the session,application variable cannot be a simple name, and in order to avoid collisions, it is usually necessary to bring the package name to the key value.
Such as:
User_data_key is used to save logged-in user information
private static final String package_name = Constants.class.getName ();
public static final String User_data_key = Package_name + ". UserData";
Typesetting/Other
1. Code style uniform adoption Eclipse default style, please select Code after use shortcut key "ctrl+shift+f" format code;
2. Each line contains only one statement. This behavior is not allowed on a single line: argv++; argc--;
3. All statement blocks in If,for,while,do while and so on should be included in {}. This makes it easy to add statements without worrying about introducing bugs because you forgot to add parentheses
4. Single line length try to avoid a line longer than 80 characters
5. Recommend a one-line declaration, as it facilitates the writing of comments
6. Avoid declaring local variables that overwrite variables declared at the previous level. For example, do not declare the same variable name in an internal code block
7. Use a blank line interval between the local variables in the method and the first statement of the method
8. Insert empty line spacing before block annotations (see "5.1.1") or single-line comments (see "5.1.2")
9. A keyword followed by a parenthesis should be separated by a space. For example: while (true) {}
10. Add a space after the comma for the parameter list. such as: Getbranch (String Branchcode, string subbranchcode);
The expression in the For statement should be separated by a space for (int i=0; i<10; i++)
12. The unary operator and the operand are not due to the addition of spaces, for example: minus sign ("-"), self-increment ("+ +") and self-subtraction ("--")
13. Forced transformation should be followed by a space MyMethod ((byte) Anum, (Object) x);

Java Programming specification

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.