Java programming specifications, java programming

Source: Internet
Author: User

Java programming specifications, java programming
I. Compiling background this document is simplified. The vast majority of content is listed in terms or forms without too many additional instructions. The code format standards follow the default coding specifications of eclipse.
2. Applicability of background developers
General provisions and regulations general provisions • simple and easy to implement
Naming principle 1. The name must be clear and be well known, such as User, Role, and UserManager.
2. Try to use an English name as the variable name. If you want to use Chinese characters, write a note.
For example, var hbType = null; // hb is the abbreviation of Chinese "currency.
3. Name the name in case-insensitive format to improve the readability of the name.
Correct: UserManager
Error: usermanager
4. Use the abbreviations as few as possible, but use them with caution if necessary.
A list of standard abbreviations should be retained and kept consistent during use. For example, if you want to use the abbreviation of the word "number", use the num format and only use this form. Note: You must maintain the list of abbreviated words.
5. The names of all files start with an uppercase letter and are mixed with uppercase and lowercase letters, such as UserList. jsp.
6. The names of all directories start with a lowercase letter and are mixed with uppercase and lowercase letters, such as userType.
7. Variable names cannot start with an underscore, such as "_ account" and "_ userName", because variables starting with an underscore may be occupied by the OWK platform as reserved words.
8. Avoid using similar or case-sensitive names.
For example, the variable names persistentObject and persistentObjects, and anSqlDatabase and anSQLDatabase should not be used at the same time.


Code annotation Principle 1. Annotations should be simple and clear, avoiding the use of decorative content. That is to say, do not use comments like ad banners.
2. The purpose of code comments is to make the code easier to be understood by developers and other subsequent developers involved in program design at the same time.
3. write comments first and then code.
The best way to write code comments is to write comments before writing code. This allows you to think about the functions and running of the code before writing it. This ensures that no comments are missing. (This is very effective if the logic of the program is a little complicated)
4. The comment information should not only include the code function, but also give reasons.
For example, the Code in Example 1 below shows that orders with amounts above $1,000 (including $1,000) can be given a 5% discount. Why? Is there a business rule that stipulates that large orders can be discounted? Is there a special time limit for such large orders, or is it always like this? Was it because of the generosity of the original program designer? Unless they are commented out somewhere (in the source code itself, or in an external document), you cannot know this.
If (grandTotal> = 1000.00)
{
GrandTotal = fig * 0.95;
}
Standard content name package structure definition =$ {package unit} [. $ {package unit}] *

Note:

1: a package is composed of one or more constructor units separated by periods (.).

2: A package unit is composed 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}
• All package names are in lowercase, for example, com. cmb. zct. tx. OA. common is not allowed. however, in some cases, uppercase letters are allowed, that is, when a package unit is composed of multiple phrases. for example: com. cmb. zct. tx. oa. userType.
Class • use a full English descriptor. The first letter of all words must be in uppercase and lowercase letters.
• The class name is a noun or noun phrase, such as LogManager.
• The tool class ends with Util. For example, FileUtil or StrUtil.
• The Exception class ends with an Exception. For example, RootDirNotExistsException
• Abstract class name starts with Abstract AbstractGenerator
• The Factory class ends with a Factory, such as ConnFactory

• Similar interface names, case-insensitive mix ..

Method • the name of the member function should use a complete English descriptor, which is used in combination with uppercase and lowercase: the first letter of all intermediate words is capitalized. The first word of the member function name often uses a verb with a strong action color. The first word is in lowercase. For example, getUserInfo and removeEquipment
Parameter variables Start with lowercase p
For example
Public void sendMessage (String pMessage ){
...............
}
Note: The parameter variables of javabean do not contain p.
Constant name Complete uppercase English Words, Connect words with underscores.
MAX_VALUE, DEFAULT_START_DATE
The directory name is the same as the package name and starts with a lower-case letter. If multiple words constitute a directory name, the words after 2nd start with an uppercase letter. For example, user and userType Directories
Naming rules for similar names of file names, starting with an upper-case letter, and combining uppercase and lowercase letters. For example: EquipmentList. jsp
Naming constraints for module-related files. For convenience, $ {MODEL_NAME} represents the name of the actual module. The file names must meet the format requirements in the following table.
File Format example
Service 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




Module configuration file Spring configuration file $ {MODEL_NAME}. spring. xml User. spring. xml
Sqlmap configuration $ {MODEL_NAME}. sqlmap. xml User. sqlmap. xml
Seed File $ {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 Annotation
* @ Param I
*/
Public Test (int I ){

}

/***
* Method Annotation
*
*/
Public void printInfo (){

}

}

Note:
• The first line is copyright information.
• A blank line defines the package name
• A blank line declares the class to be imported
• Write class comments with a blank line
• Define classes next to each other
• Define a variable with a blank line
• Define a constructor with a blank row
• Define a method with a blank row


Annotation Concept

Java programs have two types of Annotations:

Implements 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. Document comments can be converted to HTML files using the javadoc tool. This specification only imposes constraints on document comments. Program comments should be controlled by developers, but the code comments principles should be followed.

Class comments /**
*
* @ Author HO074337
* @ Version 1.0
* Creation date: 20071010
*
* Function description:
* Describes the functions of the class.
*
* Known issues:
* If a class has any outstanding problems, it should be explained to allow other developers to understand the shortcomings/difficulties of the class.
* The reason for not solving the problem should also be indicated.
*
* Maintenance history:
* Lists the authors of dates and classes and the modification summary. The purpose of this operation is to enable the maintenance programmer to understand
* Who made the changes to the class?
* For example:
* Huangyh 20071010
* Added the getUserById (String) method, which can be used to obtain user objects.
*
* Zhangw 20071008
* Set the private method removeUser () to public because it is required in the XX module.
*
*/

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 use the document annotation symbol, because the annotation information needs
Export to document.
Private variable. You can use single-line comments, multi-line comments, or document comments without restrictions.


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

Method comments /**
* Function description:
* What functions does the method provide.
*
* Known issues:
* If there are some problems with the implementation of the method, you need to describe it here to facilitate subsequent maintenance personnel
* Solve or circumvent the problem.
*
* Example:
* Simple function call example
*
* @ Param pMsg parameter name parameter description
* @ Return value description
* @ Exception description
*/


Task annotation uses TODO in annotations to identify some unimplemented (bogus) but work (works) content. Use FIXME to identify some false and incorrect content.
For example :/**
* TODO: XXX validity test.
*/
/**
* FIXME: This code has serious performance problems and must be fixed before the system is officially released.
*/
These labeled information can be viewed in the Tasks view of eclipse.
 
Exception
1. All business exceptions (account does not exist, password errors, etc.) must be derived directly or indirectly from com. cmb. zct. common. exception. BusinessException
2. All system exceptions (primary key conflicts, SQL statement syntax errors) must be derived directly or indirectly from com. cmb. zct. common. exception. SysException.

Logs 1. Do not use System. out. println/System. err. println to output debugging information.
2. Use common log to output logs in a unified manner
3. Definitions of log objects

Private final Log log = LogFactory. getLog (BaseJDBCDAO. class );
Or
Private final static Log log = LogFactory. getLog (BaseJDBCDAO. class );


The encoding method involves the encoding method. All of them use UTF-8 encoding.
Programming conventions
1. The class member variables are not set to public unless they are static final constants.
2. Use the class name to access static methods rather than objects. For example, StringUtil. trim.
3. Set the constructor of the tool class to private to prevent the client from constructing an object to call the tool method.
4. the numeric constant located in the for loop as the counter value. Except for-and 1, the constant variable should not be directly written into the code.
5. In general, 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
6. for methods that return List/Set/Map, if no record exists in the Set, an empty List/Set/Map is returned instead of null. in java. util. the Collections class contains three empty objects: EMPTY_LIST, EMPTY_SET, and EMPTY_Map.
7. The key value of the session and application variables cannot be a simple name. To avoid conflicts, we usually need to include the package name for the key value.
For example:
USER_DATA_KEY is used to save login user information
Private static final String PACKAGE_NAME = Constants. class. getName ();
Public static final String USER_DATA_KEY = PACKAGE_NAME + ". userData ";
Typographical/others
1. The Code style adopts the default Eclipse style. Select the code and press CTRL + SHIFT + F to format the code;
2. Each row contains only one statement. This is not allowed in a row: 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 due to forgetting to add parentheses.
4. Avoid the length of a single line exceeding 80 characters
5. A declaration is recommended for one row, as this facilitates writing comments.
6. 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.
7. Use a blank line interval between the local variable in the method and the first statement of the method.
8. Insert blank row intervals before block annotations (see "5.1.1") or single row annotations (see "5.1.2 ")
9. A keyword followed by parentheses should be separated by spaces. For example, while (true ){}
10. Enter a space after the comma in the parameter list. For example, getBranch (String branchCode, String subbranchCode );
11. The expressions in the for statement should be separated by spaces for (int I = 0; I <10; I ++)
12. There is no space between the unary operator and the operand, such as: negative sign ("-"), auto-increment ("++"), and auto-Subtract ("--")
13. After the forced transformation, a space myMethod (byte) aNum, (Object) x) should be followed );

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.