Java Development specification summary_code coding specification, java Coding

Source: Internet
Author: User

Java Development specification summary_code coding specification, java Coding

It is a good habit to gradually develop codes.

1. Basic Principles

Mandatory principle:
1. The StringBuilder must be used for string addition;
2. try... Catch usage

Try {} catch {Exception e. printStackTrace ();} finally {} // It Can Be Used in the Action on the outermost layer, and will not be used elsewhere;
Try {// program code} catch (Exception e) {// It is null and nothing is written} // It is forbidden to be used in any scenario
Try {} catch {Exception e throw new runtimeException (e); // the most preferred method} finally {}

1. After capturing, do not capture exceptions if you do not know what to do or how to handle them, and leave them to the outbound layer for capturing and processing;
2. If the return type is set, you must use the generic type in the method declaration. You must specify in javadoc the conditions in which null is returned and under which conditions an empty set is returned.
3. for methods and variable declaration scopes, the following priorities should be adopted: private, protected, and public. For variables, the following priorities should be adopted: local variables, instance variables, and class variables, if you must use instance variables or class variables, you must ensure thread security. If possible, use ThreadLocal to save instance variables or class variables;
4. If it is not necessary, do not define variables or new objects in the loop; try to get new objects at the last moment;
5. If not required, do not use try… in a loop... Catch;
6. The complex logic should be annotated using line comments in the class. Block comments (/**/) are definitely not allowed in java code;
7. The name of the Java class must contain uppercase letters, uppercase letters, and uppercase letters.
8. jsp file names must all be in lower case;
9. the bean configuration file name of Spring must be in lowercase in the format of xxx. bean. xml, xxx. bean. <bean id = "" in the xml configuration file. The id here is to put the first letter of the class name in lowercase here.
10. The configuration file name of xwork must be in lower case and written in xwork_xxx.xml format. XXX is the abbreviation of the business name;
11. log processing,

If (log. isDebugEnabled () ex. printStackTrace (); elselog. error ("delete from database: [" + entity. getClass (). getName () + "] instance failed", daex); throw new PersistenceException ("delete from database: [" + entity. getClass (). getName () + "] instance failed", daex );

12. It is strictly prohibited to use System. out. println () for debugging output in the Code. To use debugging information, you must use log. debug (). Use log.info () to output necessary information;
13. Do not use useless import in the class. You can use the IDE tool for optimization and format the code before submitting the class;
14. classes with business logic processing must be written into the junit unit test class;
15. international support: the ftl template does not allow Chinese characters to appear. All the characters must be placed in the corresponding properties file, and the properties file should be placed in the same directory as the Action class; ftl encoding should all adopt the UTF-8 format; properties File Name: Chinese: Action name + "_ zh" + "_ CN ". properties: Action name + "_ en" + "_ US ". properties
16. A program file should not exceed 2000 lines
17. minimize the scope of the object as much as possible, so that the visible scope and lifetime of the object will be as small as possible. If you do not want to prioritize local variables, there is no way to use global variables, threadLocal is preferred.
18. A method has a single function, and different functions are encapsulated into different methods.
19. handle exceptions or conversion exceptions as much as possible. Do not blindly package exceptions.
20. If the object must be cleared in a specific range (instead of being recycled as garbage), use the try block with the finally clause to clean it in the finally clause.
21. to organize some logic-related classes together, you can consider placing the definition of one class in the definition of another class, in this case, we recommend that you use internal classes (such as event responses in the interface layer ). The internal class has access to all the members of the peripheral class.
22. It is best to use the getter/setter method to access member variables, so as to ensure access legitimacy and code adjustment.
23. Select an interface instead of an abstract class or a specific class. If you know that something will become a base class, you should first design them as interfaces. You must modify it to a specific or abstract class only when you must put the method definition or member variable. Interfaces are only related to the actions (Protocols) the customer wants, while classes tend to focus on implementation details.
24. Use the container provided by the java standard library. Proficient in their usage will greatly improve work efficiency. Select ArrayList first to process the ordered structure, select HashSet to process the set, select HashMap to process the associated array, and select the sorted list to process the stack and queue. It optimizes the ordered access, the cost of inserting and deleting data into the List is small, but random access is slow. When using the first three, we should convert them to List, Set, and Map, so that we can implement them in other ways when necessary.
25. array is the most efficient way to store and randomly access object reference sequences. However, when an array object is created, the size of the array is fixed, if a new array is created for copying when the space is insufficient, the efficiency is higher than that of ArrayList. Therefore, you must specify the application scenario.
26. Use the "private" and "protected" keywords whenever possible. Once you mark the library features (including classes, methods, and fields) as public, you will no longer be able to remove them. In this way, the Implementation changes have the least impact on the derived class. It is especially important to maintain the Private nature when dealing with multithreading, because only Private fields are protected, you don't have to worry about being damaged by usage that is not controlled by synchronization.
27. Prohibit background service code from using the following code

try{    something()}catch(Exception ex){}new Exception()

2. class writing specifications

Class Structure, generally in the following order:
1. Constant Declaration
2. static variable Declaration
3. member variable Declaration
4. Constructor
5. Finalize Part
6. Member Methods
7. Static Methods
8. This sequence is recommended and can be modified according to a certain scale in actual development. The principle is that the program is easier to read. For example, sort methods by importance, alphabetically, or by relationship between methods.
9. Each method (including constructor and finalize) is a segment. Multiple variable declarations form a segment by logic, and the segments are separated by blank lines.
10. When declaring a class, you should point out its Access Control. Generally, there is no modifier, public, or private.
11. The majority of methods must be isolated by blank lines.
12. When writing generic classes, follow the standard format. Including defining equals (), hasCode (), toString (), Clone (implementing the Cloneable Interface), and implementing the Comparable and Serialiable Interfaces
13. Use final whenever possible for classes that do not need to be inherited during design.

3. Variable writing specifications

1. Use private as much as possible for member variables
2. Each variable Declaration/definition occupies one line (except for parameter variables), as shown in

int a;int b;

Easier to read and locate bugs than int a and B.

3. Local variables must be initialized before use. They are generally initialized during declaration.
4. The variable declaration should be placed at the beginning of the program block.

For example

public void myMethod() {  int int1 = 0; // beginning of method block  if (condition) {    int int2 = 0; // beginning of "if" block    ...  }}

One exception is that in the for statement, the definition declaration not only occupies one row, but also inside the expression, completely generated using ipvs, such:

for(int i = 0; i<100; i++)

5. The declaration of the array adopts the <data type [] + variable name> method, as shown in figure

char[] buffer;

Instead

char buffer[];

4. method writing specifications

1. Do not use public member variables easily for member methods. The main modifiers are public, private, protected, and none.
2. The methods and function bodies in the blank method can be in one row. For example: void func (){}
3. There is a blank line between the method and the method.
4. The method document comment should be placed before the method, and a line cannot be blank.
5. avoid too many parameter lists and try to keep them within five. If multiple parameters need to be transferred, an object containing these parameters is used for transmission to improve the readability and scalability of the program.
6. the circulating potential set in the method cannot exceed two layers.
7. Use final whenever possible for classes that do not require subclass to be overloaded during design.
8. Try to minimize the number of lines of code in each method to more than 100 lines (valid lines of code, excluding comments), but ensure the integrity of the logic.
9. The method in the interface is protected by default. The method is exposed to public only when it is confirmed that the packages of other subsystems will call the methods in the interface of their own subsystems.

5. language usage and writing specifications

1. Avoid defining variables with the same name as variables in the previous scope.
2. Separate methods with an empty line
3. Local variables are declared at the time of use, and local variables and static variables are initialized at the same time.
4. Place the constant number before the comparison expression as follows:

if(“simpleCase”.equals(obj))…if(null == obj)….

5. Do not perform complex operations in return statements.
6. switch statement, which requires a default Branch

 

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.